【问题标题】:Vue.js method undefined in componentVue.js 方法在组件中未定义
【发布时间】:2017-09-12 07:30:26
【问题描述】:

我正在尝试将 click 方法作为道具传递给我组件的孩子的孩子。但是,如果该方法不带任何参数,它似乎工作正常。但是,如果它需要参数,Vue.js 会向我发送Invalid handler for event "click": got undefined 错误。

这是我的顶级组件:

  new Vue({
    el: '#app',
    created: function () {
    },
    methods: {
      action1: function () {
        console.log('--action 1--')
      },
      action2: function (word) {
        console.log('--action 2--', word)
      }
    }
  });

这是我的子组件:

  Vue.component('parent-component', {
    template: '#parent-component',
    data () {
      return {
        menuItems: [
          {
            label: 'Action 1',
            onClick : this.action1
          },
          {
            label: 'Action 2',
            onClick : this.action2('two')
          }
        ]
      }
    },
    props: ['action1', 'action2']
  });

  <template id="parent-component">
    <action-menu :actions="menuItems"></action-menu>
  </template>

这是我最底层的组件:

  Vue.component('action-menu', {
    template: '#action-menu',
    props: ['actions'],
  });

<template id="action-menu">
  <div>
    <div v-for="action in actions">
      <button @click="action.onClick">{{ action.label }}</button>
    </div>
  </div>
</template>

这是我的小提琴 - http://jsfiddle.net/11sfg1p8/ - 注意第一个按钮是如何工作的,但第二个按钮没有,唯一的区别是第二个按钮带有一个参数。有人知道发生了什么吗?

提前致谢!

【问题讨论】:

    标签: javascript vue.js components


    【解决方案1】:

    在子组件内部,menuItems的第二个元素有一个onClick属性,它不是函数而是函数的返回值。

    密切注意区别:

    menuItems: [
          {
            label: 'Action 1',
            onClick : this.action1 // assigning a function
          },
          {
            label: 'Action 2',
            onClick : this.action2('two') // assigning a value
            // because of invocation of the function, 
            // which essentially returns undefined.
          }
        ]
    

    undefined 被返回是因为函数:

    action2: function (word) {
      console.log('--action 2--', word)
    }
    

    什么都不返回。 因此:

    事件“点击”的无效处理程序:未定义

    如果您打算像在此 fiddle 中那样使用它,您可以 bind 将参数 two 传递给函数。

    【讨论】:

    • 很确定你是指那个小提琴中的this.action2.bind(null, 'two')(或者你想要的任何this)。
    • @BertEvans 哦,抱歉,this.action2.bind(this, 'two') 可能是更好的选择?
    • bind 的第一个参数是 this 将在绑定函数中的内容。你是说this 应该是two
    • 这取决于this 需要什么(您希望this 引用什么)。
    • 如果函数中不使用this,那么bind(null, ...)是可以接受的。请参阅您链接的 MDN 文档的“部分应用函数”部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-25
    • 2017-07-08
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多