简体   繁体   中英

passing function as prop in vuejs

So i am creating a base "TableComponent", with selectable rows etc. This TableComponent takes a prop called "buttons".
The TableComponent expects the buttons to be an array of objects like this:

buttons: [{
    label: 'Manage Themes',
    click: () => {
        if(this.selectedRows.length) {
            this.$router.push({ name: 'ManagePageOptions', query: { concernable_type: this.type, concernable_ids: this.selectedRows.map(row => row.id).join(',') }});
        } else {
            alert('Please select 1 or more company or user');
        }
    }
}]

And so in the table component, a row of buttons is created based on what is passed like so:

<b-button v-for="button in this.buttons" @click="button.click" :key="button.label"> {{ button.label }} </b-button>

Problem is that in the buttons click function, "this" refers to the parent component, and so i don't have access to the selected rows etc.

EDIT: I have found that just passing "this" to the click function solves it. Not sure if it is wise though.

buttons = [{
    label: 'Manage Pages',
    click: (vm) => {
        if(vm.selectedRows.length) {
            vm.$router.push({ name: 'ManagePageOptions', query: { concernable_type: vm.type, concernable_ids: vm.selectedRows.map(row => row.id).join(',') }});
        } else {
          alert(Lang('Please select 1 or more company or user'))
        }
    }
}];

TableComponent data:

data() {
    return {
      selectedRows: [],
      m_this: this,
    };
  },

_

<b-button v-for="button in this.buttons" @click="button.click(m_this)" :key="button.label"> {{ button.label }} </b-button>

I agree with comments that there are better ways to do this, scoped slots is probably the best....

But, if you really want to pass functions like that you need:

  1. Change handler definition from click: () => {} to click: function() {} - reason is that this works completely different in arrow functions and as a result this is bound to the parent Vue component

  2. When passing handler into button component (inside TableComponent template), bind the handler to this of your TableComponent as described here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM