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")
}
}
}
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.