Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js Use method in v-for

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!

like image 573
Sander Van Keer Avatar asked Aug 02 '17 12:08

Sander Van Keer


People also ask

How do I use a Vue method?

A Vue method is an object associated with the Vue instance. Functions are defined inside the methods object. Methods are useful when you need to perform some action with v-on directive on an element to handle events. Functions defined inside the methods object can be further called for performing actions.

How do you call a method in Vue component?

To call a method in a child component with Vue. js, we can pass in a prop from the parent component to its child. Then in the child component, we watch the prop's value and run the method we want. in the child component to register the testProp prop and add the sayHello method.

What is V for in VueJS?

v-for directive is a Vue. js directive used to loop over a data usually an array or object. First, we will create a div element with id as app and let's apply the v-for directive to an element with data.

What is V modal in VueJS?

Vue v-model is a directive that creates a two-way data binding between a value in our template and a value in our data properties. A common use case for using v-model is when designing forms and inputs. We can use it to have our DOM input elements be able to modify the data in our Vue instance.


1 Answers

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

like image 200
Xiao Da Avatar answered Oct 02 '22 12:10

Xiao Da