Search code examples
vue.jscomponentsvuejs2vue-component

how to get the component instance within an @click event?


I have a button in a Vue component

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

within it's handler I want to invoke other methods of the component. however, even though I can call deleteItem which is itself a component method, I cannot get at the actual component for other methods.

is there a way to pass something like a $component param to the @click event?

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
    })
  },

Solution

  • I think the problem is the arrow function as commented

    See an example here using function:

    https://jsfiddle.net/rvp6fvwp/

    Arrow function is bound to the parent context as said here https://v2.vuejs.org/v2/guide/instance.html#Properties-and-Methods

    Don’t use arrow functions on an instance property or callback (e.g. vm.$watch('a', newVal => this.myMethod())). As arrow functions are bound to the parent context, this will not be the Vue instance as you’d expect and this.myMethod will be undefined.