所以我有这个<Dialog />扩展 vuetify<v-dialog />默认值的组件。
为了避免必须将onClose方法传递给DialogContent组件,我宁愿它$emit('close')。
但我无法让我的插槽监听此事件。:(
这是代码:
// Dialog.vue
<template>
<v-dialog
v-bind="$attrs"
v-model="dialog"
>
<!-- forward other slots -->
<template
v-for="(_, slot) of otherSlots"
v-slot:[slot]="scope"
>
<slot :name="slot" v-bind="scope" />
</template>
<template v-slot:default="{ on, attrs }">
<slot name="default" v-on="on" v-bind="attrs" @close="onClose" />
</template>
</v-dialog>
</template>
<script>
import {reject} from '@/utils/object';
export default {
inheritAttrs: false,
computed: {
otherSlots() {
return reject(this.$scopedSlots, 'default');
},
},
data() {
return {
dialog: false,
}
},
methods: {
onClose() {
this.dialog = false;
}
},
}
</script>
Run Code Online (Sandbox Code Playgroud)
用法:
<Dialog persistent>
<template v-slot:activator="{ on, attrs }">
<v-btn
v-bind="attrs"
v-on="on"
>
My button
</v-btn>
</template>
<DialogContent />
</Dialog>
Run Code Online (Sandbox Code Playgroud)
onClose从未被调用过。
知道为什么吗?
这是一个重现该问题的沙箱:https ://codesandbox.io/s/pass-event-listener-to-slot-ktemg9
谢谢
Sooo我终于成功地做了我想做的事:
Dialog.vue:
<template>
<v-dialog>
<slot name="default" :onClose="onClose" />
</v-dialog>
</template>
Run Code Online (Sandbox Code Playgroud)
用法:
<template v-slot:default="{onClose}">
<DialogContent @close="onClose" />
</template>
Run Code Online (Sandbox Code Playgroud)
或者有一个更像 vuetify 的语法:
Dialog.vue:
<template>
<v-dialog>
<slot name="default" :on="{close: onClose}" />
</v-dialog>
</template>
Run Code Online (Sandbox Code Playgroud)
用法:
<template v-slot:default="{on}">
<DialogContent v-on="on" />
</template>
Run Code Online (Sandbox Code Playgroud)
我希望这些道具(或事件)可以被转发而不必显式传递它们,但不幸的是这似乎不可能。:( 否则 vuetify 会为其activator插槽执行此操作。