[英]Vue.js component call a method inside data property
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 实例 (
this
) 作为参数传递给数据函数data: (vm) =>
然后使用它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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.