[英]passing function as prop in vuejs
So i am creating a base "TableComponent", with selectable rows etc. This TableComponent takes a prop called "buttons".所以我正在创建一个基本的“TableComponent”,带有可选择的行等。这个 TableComponent 需要一个名为“buttons”的道具。
The TableComponent expects the buttons to be an array of objects like this: TableComponent 期望按钮是一个对象数组,如下所示:
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.问题是在按钮单击功能中,“this”是指父组件,因此我无权访问选定的行等。
EDIT: I have found that just passing "this" to the click function solves it.编辑:我发现只需将“this”传递给 click 函数就可以解决它。 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:但是,如果你真的想传递这样的函数,你需要:
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将处理程序定义从
click: () => {}
更改为click: function() {}
- 原因是this
在箭头函数中的工作方式完全不同,因此this
绑定到父 Vue 组件
When passing handler into button component (inside TableComponent
template), bind the handler to this
of your TableComponent
as described here当传递到处理程序按钮组件(内
TableComponent
模板),绑定的处理程序this
您的TableComponent
如这里所描述
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.