![](/img/trans.png)
[英]How can I change data value from one component to another component in Vue Js?
[英]how can I reference a method from the same component in the data of the component vue js
我有以下組成部分
<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
屬性。 因此,在模板中,我想調用當某人單擊特定項目時我們指定的任何功能。
那么,如何在相同組件的數據部分中引用該方法? 截至目前,我正在開始准備undefined
錯誤。
讓我知道是否需要進一步澄清
嘗試將方法名稱添加為類似於操作值的字符串,並在模板中使用@click="handleAction(item.action)"
:
<template>
<li v-for="(item, i) in menu" :key="i" @click="handleAction(item.action)">
{{menu.title}}
<li>
</template>
<script>
export default {
data: () => ({
menu: [
{title: 'Start Preparing', action:'startPrepare'}, //how do I reference the method here?
{title: 'Cancel Order'},
],
}),
methods: {
handleAction(actionName){
this[actionName]();
}
startPrepare: function (orderId) {
console.log("start")
}
}
}
</script>
在這里我想主要的問題是,您使用的是箭頭功能為您的data
,它不能被綁定到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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.