首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 ><MenuItems />缺少父<Menu />组件错误( MenuItems在插槽中)

<MenuItems />缺少父<Menu />组件错误( MenuItems在插槽中)
EN

Stack Overflow用户
提问于 2022-06-30 09:05:12
回答 1查看 177关注 0票数 1

我正在Vue3中创建一个名为“下拉”的组件。

下拉组件依次使用其他组件:来自headlessui/vue库菜单、MenuItems、MenuItem和MenuButton

我的想法是,您可以将任何内容放入下拉中,这就是为什么我创建了一个名为#contentdropdown的槽。

问题是,当我将这个插槽内容传递给下拉组件时,Vue会给出以下错误:

< MenuItems />缺少父< Menu />组件

这是我的下拉组件代码:

代码语言:javascript
复制
<template>
  <Menu as="div" class="relative inline-block text-left">
    <div>
      <MenuButton class="btn inline-flex justify-center w-full text-sm" :class="'btn-'+variant">
        Options
        <ChevronDownIcon class="-mr-1 ml-2 h-5 w-5" aria-hidden="true" />
      </MenuButton>
    </div>

    <transition enter-active-class="transition ease-out duration-100" enter-from-class="transform opacity-0 scale-95" enter-to-class="transform opacity-100 scale-100" leave-active-class="transition ease-in duration-75" leave-from-class="transform opacity-100 scale-100" leave-to-class="transform opacity-0 scale-95">
      <slot name="contentdropdown"></slot>
    </transition>
  </Menu>
</template>

<script>
import { Menu, MenuButton } from '@headlessui/vue'
import { ChevronDownIcon } from '@heroicons/vue/solid'
import { vVariantProp } from '../../../../constants'
import { reactive, computed } from 'vue';

export default {

    name: 'dropdown',

    props: {
  
        ...vVariantProp,
    },

    setup(props) {

        props = reactive(props);
    
        return {
           
        }
    },
    
};
</script>

为什么它需要名为Menu的父组件?如果实际上我已经在绘制组件中的插槽,并在下拉组件中导入它。

这就是我如何通过其#contentdropdown槽将内容传递给下拉组件的方式:

代码语言:javascript
复制
<Dropdown v-bind="{'variant':'primary'}">
          <template #contentdropdown>
            <MenuItems class="origin-top-right absolute right-0 mt-2 w-56 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 focus:outline-none">
              <div class="py-1">
                <MenuItem>
                  <a href="#" class="block px-4 py-2 text-sm">Subitem1</a>
                </MenuItem>
                <MenuItem>
                  <a href="#" class="block px-4 py-2 text-sm">Subitem2</a>
                </MenuItem>
              </div>
            </MenuItems>
          </template>
        </Dropdown>
EN

回答 1

Stack Overflow用户

发布于 2022-06-30 10:22:13

错误<MenuItems /> is missing a parent <Menu /> component不是Vue特定的错误。这是headlessui/vue - 来源引发的错误。

MenuItems组件(以及MenuButon等-参见文档)被设计用于Menu组件中。它使用inject通过给养组件访问状态给养。你对此无能为力--它是这样设计的。

问题是Vue中的插槽内容(最后一个代码示例中的<template #contentdropdown>中的所有内容)总是在父范围中呈现

父模板中的所有内容都在父范围中编译;子模板中的所有内容都在子范围中编译。

这意味着呈现为槽内容的MenuItems不能访问由在Dropdown组件中呈现的Menu组件所呈现的数据provide

我看不出有什么办法能克服这个限制。您需要更改您的设计(或者向headlessui/vue维护人员描述您的用例,并要求他们实现与子组件共享MenuContext的替代方法--例如使用插槽道具)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72813097

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档