我有一个使用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>发布于 2021-04-01 11:03:43
我最终使用了watch route方法。
watch: {
'$route' () {
// this will close the dropdown
this.dropdownPopoverShow = false,
// this will close the mobile menu on page change
this.isOpen = false
}发布于 2021-03-29 05:01:32
您可以使用Vue路由器实例上的afterEach挂钩,将一个方法设置为在每次页面更改时运行。我建议将其设置为Nuxt中的一个插件,并将dropdownPopoverShow从您的导航组件移动到存储中。
将dropdownPopoverShow移动到存储中,以便可以在您的nav组件之外引用它。
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
}
}在您的nav组件中,调用存储中的突变。
methods: {
toggleDropdown() {
this.$store.commit('toggleDropdown')
}
}最后,创建一个插件,在每次路由更改后将dropdownPopoverShow设置为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' } ]https://stackoverflow.com/questions/66845119
复制相似问题