我有以下组件
<template>
<li v-for="(item, i) in this.menu" :key="i" @click="item.action()"> //trying to call the method in the component
{{menu.title}}
<li>
</template>
<script>
export default {
data: () => ({
menu: [
{title: 'Start Preparing', action: this.startPrepare}, //how do I reference the method here?
{title: 'Cancel Order'},
],
}),
methods: {
startPrepare: function (orderId) {
console.log("start")
}
}
}
</script>
正如您在评论部分中看到的,我在数据部分有一个 menu
,它有一个 title
和 action
属性它。因此,在模板中,我想在有人单击该特定项目时调用我们指定的任何函数。
那么如何在该组件的数据部分引用同一组件中的方法呢?截至目前,我遇到了开始准备是未定义
错误。
如果需要任何进一步说明,请告诉我
最佳答案
我认为这里的主要问题是您为 data
使用了箭头函数,它无法绑定(bind)到 Vue 实例。您需要使用普通函数来代替..
export default {
data() {
return {
menu: [{
title: 'Start Preparing',
action: this.startPrepare
}, //how do I reference the method here?
{
title: 'Cancel Order'
},
],
}
},
methods: {
startPrepare: function(orderId) {
console.log("start")
}
}
}
<template>
<li v-for="(item, i) in this.menu" :key="i" @click="item.action()"> //trying to call the method in the component
{{menu.title}}
<li>
</template>
关于javascript - 如何在组件vue js的数据中引用同一组件的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57357821/