【问题标题】:how can I reference a method from the same component in the data of the component vue js如何在组件vue js的数据中引用来自同一组件的方法
【发布时间】:2019-12-12 22:21:35
【问题描述】:

我有以下组件

<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 属性。因此,在模板中,当有人单击该特定项目时,我想调用我们指定的任何函数。

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

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

【问题讨论】:

    标签: javascript vue.js vuejs2 vuetify.js


    【解决方案1】:

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

    【讨论】:

    • 我觉得这个比较合适,谢谢
    【解决方案2】:

    尝试将方法名称添加为类似操作值的字符串,并在模板中访问它,如@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>
    

    【讨论】:

    • error in v-on handler: "TypeError: [item.action] is not a function"
    • 我尝试过这样做,但我遇到了与上面评论相同的错误
    • 谢谢,它确实有效。我现在将使用它。但我觉得这是一个黑客。让我知道是否有任何本地方式做这件事:)
    • 不客气,这不是 hack,因为 JS 更灵活,可以让你以不同的方式访问字段
    猜你喜欢
    • 1970-01-01
    • 2020-04-05
    • 2019-01-03
    • 2023-03-16
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 2019-09-20
    • 2018-02-19
    相关资源
    最近更新 更多