Vue.js Use method in v-for

22,420

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???

Share:
22,420
Sander Van Keer
Author by

Sander Van Keer

Updated on August 01, 2022

Comments

  • Sander Van Keer
    Sander Van Keer almost 2 years

    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!