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!
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.
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.
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.
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.
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>
dataBar
in data myMethod
with variable bar
in another method newMethod
dataBar
(the axios response) in newMethod
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
???
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With