我想实现带有子菜单项的动态菜单。为此,我定义了一个数据对象,它包含所有带有子菜单项的菜单项。
<script setup lang="ts">
import { ref } from "vue";
const menu = ref([
{
id: 1,
name: "Programs",
submenu: ["Sub-1", "Sub-2", "Sub-3", "Sub-4"],
},
{ id: 2, name: "Events", submenu: [] },
{ id: 3, name: "Publications", submenu: [] },
{ id: 4, name: "Tutorials", submenu: ["Tut-1", "Tut-2"] },
{ id: 5, name: "About Us", submenu: [] },
]);
</script>
在模板内,我在各自的html标签内调用这些菜单和子菜单:
<template>
<div class="container mx-auto max-w-screen-xl">
<!--Navbar-->
<div
class="menu-line align-baseline justify-around hidden w-full mb-2 md:block"
>
<ul
class="font-BPGBannerCaps text-sm flex flex-col justify-end tracking-wide bg-gray-50 border border-gray-100 md:flex-row md:space-x-8 md:mt-0 md:mb-0 md:text-base md:font-medium md:border-0 md:bg-white"
>
<li v-for="item in menu" :key="item.id">
<button
id="dropdownNavbarLink"
data-dropdown-toggle="dropdownNavbar"
class="flex justify-between items-center w-full font-medium text-gray-700 rounded hover:bg-gray-100 md:hover:bg-transparent md:border-0 md:hover:text-blue-700 md:p-0 md:w-auto"
>
{{ item.name }}
<svg
v-if="item.submenu.length"
class="ml-1 w-5 h-5"
aria-hidden="true"
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
clip-rule="evenodd"
></path>
</svg>
</button>
<!-- Dropdown menu -->
<div
id="dropdownNavbar"
class="hidden z-10 w-56 font-normal bg-white rounded divide-y divide-gray-100 shadow"
>
<ul
class="py-1 text-sm text-gray-700 dark:text-gray-400"
aria-labelledby="dropdownLargeButton"
v-if="item.submenu.length"
>
<li v-for="subitem in item.submenu" :key="item.id">
<a href="#" class="block py-2 px-4 hover:bg-gray-100">{{
subitem
}}</a>
</li>
</ul>
</div>
</li>
</ul>
</div>
</div>
</template>
但是,会为任何菜单项显示子菜单项:
善意的建议我做错了什么,我怎么能解决这个问题。
1条答案
按热度按时间x4shl7ld1#
在子菜单中,将父菜单的键指定为
:key="item.id"
。所以当你改变子菜单时,键不会改变。Vue使用一些缓存策略来避免重新渲染,因为:键没有改变,它认为要渲染的是相同的元素。
只需将您的
:key
更新为:key="subitem"
,它应该会正确更新。