场景
最近在项目开发过程中,项目经理提了一个需求:在当前页面点击当前页面对应的(左侧)菜单时,也能刷新页面。
由于 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/index.js
{
path: '/redirect',
component: () => import('@/layout/components/redirect.vue')
},
3.菜单跳转的地方添加事件,进行相关处理:
<el-menu ... @select="selectMenuItem">
// ...
</el-menu>
methods: {
selectMenuItem(url, indexPath) {
// console.log('点击菜单刷新当前页面')
// console.log(url, indexPath)
// console.log(this.$route.fullPath)
if (this.$route.fullPath === url) {
// console.log('点击的是当前路由 手动重定向页面到')
// 点击的是当前路由 手动重定向页面到 '/redirect' 页面
this.$router.replace({
path: '/redirect',
query: {
path: encodeURI(url)
}
})
}
}
}
用此种方法,能实现真正的页面(组件)刷新,当点击同一菜单时,地址栏每次的变化都是从:http://localhost:8080/#/redirect?path=xxxxxx 至 http://localhost:8080/#/xxxxxx