单击菜单项后如何关闭下拉列表



我有一个使用 NUXT JS 和顺风 CSS 的下拉菜单 但是Nuxt-js的问题,因为它不会使用SSR更改页面,因此下拉列表不会关闭 单击菜单项时如何关闭下拉列表

这是模板

<!-- dropdown -->
<button class="mt-1 block px-2 py-1 text-white font-semibold rounded hover:bg-gray-800 sm:mt-0 sm:ml-2"
type="button" v-on:click="toggleDropdown()" ref="btnDropdownRef">
Applications
</button>
<div v-bind:class="{'hidden': !dropdownPopoverShow, 'block': dropdownPopoverShow}"
class="bg-gray-800 w-full md:w-1/5 text-white z-50 float-left py-2 list-none text-left rounded shadow-lg mt-1"
ref="popoverDropdownRef">
<NuxtLink class="mt-1 font-semibold block px-2 py-1 text-white  rounded hover:bg-gray-800 sm:mt-0 sm:ml-2" to="/applications/education">
education
</NuxtLink>
<NuxtLink class="mt-1 font-semibold block px-2 py-1 text-white  rounded hover:bg-gray-800 sm:mt-0 sm:ml-2" to="/applications/lifescience">
life sciences 
</NuxtLink>
<NuxtLink class="mt-1 font-semibold block px-2 py-1 text-white  rounded hover:bg-gray-800 sm:mt-0 sm:ml-2" to="/applications/education">
media
</NuxtLink>
<NuxtLink class="mt-1 font-semibold block px-2 py-1 text-white  rounded hover:bg-gray-800 sm:mt-0 sm:ml-2" to="/">
industries
</NuxtLink>
<NuxtLink class="mt-1 font-semibold block px-2 py-1 text-white  rounded hover:bg-gray-800 sm:mt-0 sm:ml-2" to="/">
agriculture
</NuxtLink>
</div>

这是剧本

<script>
import {
createPopper
} from "@popperjs/core";
export default {
data() {
return {
isOpen: false,
dropdownPopoverShow: false,
}
},
methods: {
toggleDropdown: function () {
if (this.dropdownPopoverShow) {
this.dropdownPopoverShow = false;
} else {
this.dropdownPopoverShow = true;
createPopper(this.$refs.btnDropdownRef, this.$refs.popoverDropdownRef, {
placement: "bottom-start"
});
}
}
}
}
</script>

我最终使用了监视路由方法

watch: {
'$route' () {
// this will close the dropdown
this.dropdownPopoverShow = false,  
// this will close the mobile menu on page change
this.isOpen = false
}

您可以使用 Vue 路由器实例上的afterEach钩子将方法设置为每次更改页面时运行。我建议将其设置为Nuxt中的插件,并将dropdownPopoverShow从导航组件移动到商店中。

dropdownPopoverShow移动到存储中,以便可以在导航组件外部引用它。

export const state = () => ({
dropdownPopoverShow: false
})
export const mutations = {
toggleDropdown(state) {
// no need for an 'if/then', just toggle the Boolean
state.dropdownPopoverShow = !state.dropdownPopoverShow
},
hideDropdown(state) {
state.dropdownPopoverShow = false
}
}

在导航组件中,调用存储中的突变。

methods: {
toggleDropdown() {
this.$store.commit('toggleDropdown')
}
}

最后,创建一个插件,在每次路由更改后将下拉列表PopoverShow设置为false。

// plugins/hideDropdown.js:
export default async ({ app, store }) => {
app.router.afterEach((to, from) => {
store.commit('hideDropdown')
});
}

请记住将插件添加到您的nuxt配置中:

plugins: [ { src: '~/plugins/hideDropdown.js', mode: 'client' } ]

对于组合 API

const route = useRoute();
watch(route, () => {
this.dropdownPopoverShow = false, 
this.isOpen = false
});

对于选项 API

watch: {
'$route' () {
this.dropdownPopoverShow = false,  
this.isOpen = false
}

最新更新