使用vuetify中的VMenu和渲染函数(作用域插槽)



我正在尝试使用Vuetify的VMenu组件,我希望当用户单击按钮时,VMenu会显示出来。就文档而言,它说我们应该添加一个作用域插槽。使用普通模板可以工作,但当我切换到渲染函数方法时,它永远不会渲染按钮。

我一直在关注Vue的文档,最终得到了:

h(VMenu, { props: { value: isMenuOpen.value } }, [
h(
"template",
{
scopedSlots: {
activator: ({ on, attrs }) => {
debugger; // it never reaches this debugger
return h(VButton, { on, attrs }, 'click me');
}
},
},
[]
),
h(VList, [h(VListItem, [h(VListItemTitle, ["Logout"])])]),
]),

我也尝试过使用非箭头功能:

scopedSlots: { activator: function({ on, attrs }) {  return h('div', 'click me');  } }

并在非箭头函数和箭头函数中返回一个简单的CCD_ 3。

如何将作用域插槽activator传递给VMenu组件?

作用域槽以{ name: props => VNode | Array<VNode> }的形式通过createElement的第二个参数的scopedSlots属性传递。在您的情况下,scopedSlots应该有两个条目:一个用于activator,另一个用于default:

import { VMenu, VList, VListItem, VBtn } from 'vuetify/lib'
export default {
render(h) {
return h(VMenu, {
scopedSlots: {
activator: props => h(VBtn, props, 'Open'),
default: () => h(VList, [
h(VListItem, 'item 1'),
h(VListItem, 'item 2'),
h(VListItem, 'item 3'),
]),
},
})
}
}

相当于这个模板:

<template>
<v-menu>
<template v-slot:activator="{ on, attrs }">
<v-btn v-bind="attrs" v-on="on">Open</v-btn>
</template>
<v-list>
<v-list-item>item 1</v-list-item>
<v-list-item>item 2</v-list-item>
<v-list-item>item 3</v-list-item>
</v-list>
</v-menu>
</template>

演示

我无法完全理解问题中描述的问题。这不是为了回答完全原创的问题,而是为了指导未来可能会遇到这个问题的用户。

我没有使用作用域插槽,而是将value道具与attach道具结合使用。这个解决方案最终毫无问题地发挥了作用。

button(
{
attrs: { "data-account-setting": true },
props: { plain: true, rounded: true, icon: true },
on: { click: onOpenMenuClick },
},
[h(VIcon, ["mdi-account-outline"])]
),
h(
VMenu,
{
props: {
value: isMenuOpen.value,
// waiting on answer on SO
// @see https://stackoverflow.com/questions/67405594/using-vmenu-from-vuetify-with-render-function-scoped-slot
attach: "[data-account-setting]",
minWidth: "300px",
left: true,
offsetY: true,
closeOnContentClick: false,
rounded: true,
},
on: {
input: (value: boolean) => {
isMenuOpen.value = value;
},
},
},
[
h(VList, { props: { dense: true } }, [
h(VListItem, { props: { to: { name: "logout" } } }, [
h(VListItemTitle, { attrs: { 'data-cy-logout': true } }, ["Logout"]),
]),
]),
]
),

最新更新