网格组件grid.js
:
<template>
<div class="grid">
...
<component v-for="c in cells" :is="c.componentName"></component>
</div>
</template>
<script>
export default {
props: {
cells: { type: Array, required: true }
}
methods: {
// the idea what I need
reEmitAllCellComponentEventWithPrefix($event) {
// add prefix
this.$emit("cell-" + $event.name, $event.data);
}
}
}
</script>
基本单元base-cell.js
(定义公共单元的道具和方法):
export default {
props: ['componentName', 'columnIndex', 'rowIndex', 'cellData', ...],
...
}
自定义单元组件custom-cell.js
(均从基本单元组件扩展,全局注册):
<template>
<dom ...>
</template>
<script>
import baseCell from "./base-cell"
export default {
extends: baseCell,
props: {
componentName: '...',
customProp1: '...',
...
},
watch: {
// a custom event example
customProp1(){
this.$emit('custom-event1', ...)
}
},
...
}
</script>
所有单元格组件都有其自己的自定义事件,可能是任何事件名称。
用法:
// dom
<div id="app">
<grid :cells="cells" @cell-custom-event1="customCellEventHandler"></grid>
</div>
// js
import grid from "./grid"
new Vue({
el: '#app',
data: { cells: ... },
method: {
customCellEventHandler($event){
...
}
},
...
})
我希望用户在使用网格组件时可以侦听带有前缀cell-
的单元组件的自定义事件。我该如何工作?
答案 0 :(得分:0)
您可以这样做:
<template>
<div class="row">
<component v-for="c in cells" :is="c.componentName" @click="onClick(c.name, c.data)"></component>
</div>
</template>
<script>
export default {
props: {
cells: { type: Array, required: true }
}
methods: {
onClick(name, data) {
this.$emit("cell-" + name, data);
}
}
}
</script>
基本上,当您浏览单元格并创建元素时,会为每个单元格添加click事件,并添加所需的任何参数,然后使用它们来发出事件。
如果您还需要“事件”数据,可以像这样$event
在@click="onClick(c.name, c.data)"
中添加@click="onClick(c.name, c.data, $event)"
,然后可以在方法上添加相应的参数onClick(name, data, e)
我希望这就是您想要的。