【问题标题】:how to get the component instance within an @click event?如何在@click 事件中获取组件实例?
【发布时间】:2018-01-28 09:57:48
【问题描述】:

我在 Vue 组件中有一个按钮

<el-button class='range-right' @click='deleteItem(item)'>delete</el-button>

在它的处理程序中,我想调用组件的其他方法。 然而,即使我可以调用 deleteItem 这本身就是一个组件方法,我也无法获取其他方法的实际组件。

有没有办法将 $component 参数传递给 @click 事件?

methods {
  deleteItem: (item, obj) => {
    let api = '/api/train/deleteItem?_id=' + item._id
    let resource = Vue.resource(api)
    let vm = this  // NOT a component
    window.delItem = this
    console.log('deleteItem.this', this)
    resource.delete(api)
    .then(items => {
      console.log('deleted')
      vm.methods.load() //<< fails
    })
  },

【问题讨论】:

标签: vue.js components vuejs2 vue-component


【解决方案1】:

我认为问题出在注释中的箭头函数

在此处查看使用function 的示例:

https://jsfiddle.net/rvp6fvwp/

箭头函数绑定到父上下文,如此处所述https://vuejs.org/v2/guide/instance.html#Properties-and-Methods

不要在实例属性或回调上使用箭头函数(例如 vm.$watch('a', newVal =&gt; this.myMethod()))。由于箭头函数是 绑定到父上下文,这不会是 Vue 实例 你会想到 this.myMethod 将是未定义的。

【讨论】:

  • 是的,就是这样。一个小小的 vue 陷阱!如果工具为此提供某种类型的警告可能会很好。
猜你喜欢
  • 2022-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多