VUE
菜单栏
Vue 项目重复点击菜单刷新当前页面
前言
当前页面点击当前页面对应的菜单时,也能刷新页面
一、为什么不能直接通过路由直接进行跳转?
由于 Vue 项目的路由机制是路由不变的情况下,对应的组件是不重新渲染的。所以重复点击菜单不会改变路由,然后页面就无法刷新了。
二、解决方案
借助重定向
利用一个空的 redirect 页面,通过判断当前路由是否与点击的路由一致,如果一致,则跳转到 redirect 页面,然后在 redirect 页面重定向回跳转之前的页面。这样就实现了页面刷新了。
1、创建一个空页面:>src/layout/components/redirect.vue
<script>
export default {
beforeCreate() {
const { query } = this.$route
const path = query.path
this.$router.replace({ path: path })
},
mounted() {},
render: function(h) {
return h() // avoid warning message
}
}
</script>
2、挂载路由:>src/router.js
const Redirect = () => import('./components/redirect.vue')
routes: [
{ path: '/Redirect ', component: '/Redirect ' }
]
3、菜单跳转的位置添加事件进行判断是否重定向:
// 菜单栏点击事件,activePath为路由地址
saveNavState(activePath) {
//获取前一次选中菜单栏路由
var oldPath = window.sessionStorage.getItem('activePath')
// 若点击的是当前路由 则重定向到 '/redirect' 页面
if (activePath == oldPath) {
this.$router.replace({
path: '/redirect',
query: {
path: encodeURI(activePath)
}
})
} else{
//正常进行跳转
window.sessionStorage.setItem('activePath', activePath)
this.$router.push('/activePath')
}
},
总结
还可通过改变路由的方式实现页面刷新,因时间有限,先列出此种解决方法。