8

I want to run a method inside a v-for in my Vue component. Example:

<div v-for="(foo,index) in bar">
      <p>{{myMethod(foo,index)}}</p>
</div>

When I do this the p-tag just stays empty. Here is my method(with an axios call):

 myMethod:function(foo,index) {
    axios.get('/myAjaxCall')
    .then((response)=> {
        //works perfectly
        alert(response.data);
        return response.data;

    })
    .catch(function (error) {
        console.error(error);
    });
   },
 }

When I alert( SomethingWithFooAndIndex), the browser is showing exactly what I need. When I remove the axios call the method seems to work

Thanks!

2
  • you're missing a closing quote on the attribute btw Commented Aug 2, 2017 at 12:24
  • This is just a simplified example, I am using them in the ajax url Commented Aug 2, 2017 at 13:08

3 Answers 3

2

I dont think you should use myMethod in v-for

axios is asynchronous

Try to do myMethod with bar in another method, get a data newbar, you can render the newbar

<div v-for="(foo, index) in dataBar"> <p>{{otherSimpleMethod(foo, index)}}</p> </div>

  1. add dataBar in data
  2. do myMethod with variable bar in another method newMethod
  3. update dataBar(the axios response) in newMethod
  4. do newMethod in mounted(I guess you want to do this after page loaded)

Or you can try nextTick

BTW, the title Vue.js Use mounted in v-for ??? maybe Vue.js Use method in v-for???

Sign up to request clarification or add additional context in comments.

Comments

1

You has issue in your code. You missed a quote <div v-for="(foo,index) in bar"> <p>{{myMethod(foo,index)}}</p> </div>

Please refer the following jsbin http://jsbin.com/wovavut/edit?html,js,output

2 Comments

You can still refer jsbin
Thanks to you I found out the axios is causing the problem. Chekc my edited question please
0

I also don't believe you should use a method in the v-for, but instead use a computed property that applies your method to the unprocessed array of your items that likely sits somewhere in data:

Vue.js 2: Computed

2 Comments

But I need the foo from the for loop in my method. And I think you can't add variables to computed functions
@SanderVanKeer: if your data comes from somewhere (either set in created or as props) you can loop/map over that and save it (enriched with maybe data from an api call or user storage) to the computed property. Alternatively you can make the computed function do everything that you need done to the raw data and then iterate over it. Can you provide more context?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.