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

标签 javascript vue.js vuejs2 vuetify.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 ,它有一个 titleaction 属性它。因此,在模板中,我想在有人单击该特定项目时调用我们指定的任何函数。

那么如何在该组件的数据部分引用同一组件中的方法呢?截至目前,我遇到了开始准备是未定义错误。

如果需要任何进一步说明,请告诉我

最佳答案

我认为这里的主要问题是您为 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/

相关文章:

vue.js - 将vuejs中的大括号更改为其他内容

javascript - 在 VueJS 中按数字 (0-9) 对我的 API 数据进行排序

javascript - 如何在vue js的更新页面中选择类

javascript - jQuery - 使 <pre> 具有其内容的宽度

javascript - backand.js 未缩小版的 CDN 地址是多少

javascript - Angularjs - 从 ng-repeated 指令访问共享服务数据

javascript - 在哪里/如何为 Vue Js 方法定义数据变量?

Javascript 不会加载包含 jQuery mobile 的链接

javascript - 路由器模板中的 Vue 计算属性

javascript - 如何使用数组中的数据在 VueJS Material 上创建 <md-select> 下拉列表?