Reputation: 458
I'd like to assign component methods to data variables, see the example code below. Sadly it does not work, what is the correct way?
<li v-for="item in items" @click="item.action">
{{ item.title }}
</li>
export default {
data: () => ({
items: [
{ title: "One", action: this.funcOne },
{ title: "Two", action: this.funcTwo },
]
}),
methods: {
funcOne() {
alert("Hi")
},
funcTwo() {
alert("Hello")
}
}
}
Upvotes: 2
Views: 868
Reputation: 1
Try to pass the vue instance (this
) as parameter to the data function data: (vm) =>
then use it action: vm.funcOne
Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
el: '#app',
data: (vm) => ({ // vm the component instance this
items: [
{ title: "One", action: vm.funcOne},
{ title: "Two", action: vm.funcTwo },
]
}),
methods: {
funcOne() {
alert("Hi")
},
funcTwo() {
alert("Hello")
}
}
})
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app" class="container">
<li v-for="item in items" @click="item.action">
{{ item.title }}
</li>
</div>
Upvotes: 3