我想向组件传递一个插槽中的按钮,它将有一个动作。例如一个具有“添加行”功能的表。
<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中所示。如何让这个模式起作用?
发布于 2018-06-11 07:24:58
要从子元素(<my-table>
)向其父元素提供数据和操作,可以查看scoped slots。
当子组件有一些与父组件无关的内部状态时,或者为子组件提供自定义属性或回调并将标记和样式留给父组件时,作用域插槽工作得非常好。
但是,在您的示例中,由于是父对象持有数据属性,因此我不确定这是否是最好的解决方案。孩子不应该改变它。
您可以简单地解析父组件上的事件。
https://stackoverflow.com/questions/50788716
复制相似问题