我想向组件传递一个插槽中的按钮,它将有一个动作。例如一个具有“添加行”功能的表。
<my-table :data="data" :cols="cols">
<button slot="add_row"></button>
</my-table>
或者,此反汇编警报:
<alert>
<button slot="close">Remove the alert</button>
</alert>
它们具有以下模板:
<div class="alert alert-info">
<slot></slot>
</div>
问题是,我希望在组件定义中,将一个事件操作绑定到<slot>
ed按钮,但仍然允许组件用户提供自己的按钮(有时甚至是一个链接、<a>
元素)。
我曾考虑为操作按钮使用一个指令,类似于下面的库:
https://bootstrap-vue.js.org/docs/components/modal
其中,模式按钮具有v-b-modal
指令。但是不知道该怎么做。
UPDATE:我正在尝试使用一个指令来实现它。这就是我目前所拥有的:https://jsfiddle.net/uvd6knLh/
Vue.component('alert', {
template: `
<div class="alert alert-info" v-if="show">
<slot></slot>
</div>`,
data() {
return {
show: true
}
},
mounted() {
// directive event
this.$root.$on("alert:close", () => this.show = false);
}
});
Vue.directive('alert-dismiss', {
inserted: function(el, binding, vnode) {
el.addEventListener("click", () => {
vnode.context.$root.$emit("alert:close");
});
}
});
所以我监听指令事件。问题是,指令事件将导致所有警报组件关闭,如jsfiddle中所示。如何让这个模式起作用?
https://stackoverflow.com/questions/50788716
复制相似问题