简体   繁体   English

如何在组件vue js的数据中引用来自同一组件的方法

[英]how can I reference a method from the same component in the data of the component vue js

I have the following component 我有以下组成部分

<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>

As you can see in the commented sections, I have a menu in the data section, it has a title and action properties in it. 如您在注释部分中所见,我在数据部分中有一个menu ,其中包含titleaction属性。 So in the template, I want to invoke whatever function we have specified when someone clicks on that particular item. 因此,在模板中,我想调用当某人单击特定项目时我们指定的任何功能。

So how do I refer a method in the same component in the data section of that component? 那么,如何在相同组件的数据部分中引用该方法? as of now, I am getting start prepare is undefined error. 截至目前,我正在开始准备undefined错误。

Let me know if any further clarifications are needed 让我知道是否需要进一步澄清

Try to add the method name as a string like action value and in the template access it like @click="handleAction(item.action)" : 尝试将方法名称添加为类似于操作值的字符串,并在模板中使用@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>

The main problem here I think is that you're using an arrow function for your data , which can't be bound to the Vue instance. 在这里我想主要的问题是,您使用的是箭头功能为您的data ,它不能被绑定到Vue的实例。 You need to use a normal function instead .. 您需要改用普通函数..

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM