Vue 向组件事件添加自定义参数
Vue 向组件事件添加自定义参数这次写前端的时候有个功能需求,用 elemet-table 自定义组件,但是要向外部传递 table 子组件的事件,如下:自定义组件 nc-table<el-table><el-table-columnv-bind="getColumnDefaultProps(col.props)"v-for="(col, index) in config.col
·
Vue 向组件事件添加自定义参数
这次写前端的时候有个功能需求,用
elemet-table
自定义组件,但是要向外部传递table
子组件的事件,如下:
自定义组件 nc-table
<el-table>
<el-table-column
v-bind="getColumnDefaultProps(col.props)"
v-for="(col, index) in config.column" :key="index">
</el-table-column>
</el-table>
现在想把el-table
的所有事件继续向外传递,也就是期望在父组件中的用法
<nc-table :config="tableConfig"
@select="select"
@cell-mouse-enter="mouseEnter"
....其他事件
>
</nc-table>
由于template中不能像 v-bind="props"
一次性传入所有props
,事件必须一条条列出来写上(有其他办法的同学欢迎留言),于是自定义组件中可以这么写
<el-table
@select="transmit(arguments, 'select')"
@select-all="transmit(arguments, 'select-all')"
@selection-change="transmit(arguments, 'selection-change')"
@cell-mouse-enter="transmit(arguments, 'cell-mouse-enter')"
@cell-mouse-leave="transmit(arguments, 'cell-mouse-leave')"
......其他事件......
>
<el-table-column
v-bind="getColumnDefaultProps(col.props)"
v-for="(col, index) in config.column" :key="index">
</el-table-column>
</el-table>
/**
* 在method中定义公共方法transmit
* arguments: 是vue中组件的事件默认参数
* ev: 是自己定义的传递的参数,也就是emit类型
**/
transmit(arguments, ev){
//将事件再抛出去
this.$emit(ev, ...arguments)
},
注意 $emit
的参数,要使用...arg
而不是 直接arg
,这样才能在父组件的事件处理函数中列出参数名,不然传入会把第一个参数变成数组
,其他参数为undefine
这样在父组件中引用自定义组件,就能像在el-table
上写事件处理一样啦
更多推荐
已为社区贡献2条内容
所有评论(0)