需求:“在當前頁面點擊當前頁面對應的菜單時,也能刷新頁面。”
由于 Vue 項目的路由機制是路由不變的情況下,對應的組件是不重新渲染的。所以重復點擊菜單不會改變路由,然后頁面就無法刷新了。
方案一
在vue項目中,如何實現再次點擊,刷新右側內容,我使用了vue中的[provide/inject]
1. 在父組件中設置provide
?2.還有別忘了methods中reload()這個方法
?3.在左側菜單組件中通過inject調用
?
參考文檔vue+element的后臺項目 實現再次點擊左側菜單欄,刷新右側內容_element右側組件刷新-CSDN博客
方案二
借助重定向
點擊左側子菜單時,菜單欄會折疊再刷新一下
利用一個空的?
redirect
?頁面,通過判斷當前路由是否與點擊的路由一致,如果一致,則跳轉到?redirect
?頁面,然后在?redirect
?頁面重定向回跳轉之前的頁面。這樣就實現了頁面刷新了。
-
創建一個空的頁面:
src/layout/components/redirect.vue
<script> export default {beforeCreate() {const { query } = this.$routeconst path = query.paththis.$router.replace({ path: path })},mounted() {},render: function(h) {return h() // avoid warning message} } </script>
-
掛載路由:
src/router/index.js
{path: '/redirect',component: () => import('@/layout/components/redirect.vue') },
-
菜單跳轉的地方添加事件,進行相關處理:
<el-menu ... @select="selectMenuItem">// ...
</el-menu><script>
export default {methods: {selectMenuItem (url, indexPath) {if (this.$route.fullPath === url) {// 點擊的是當前路由 手動重定向頁面到 '/redirect' 頁面this.$router.replace({path: '/redirect',query: {path: encodeURI(url)}})} else {// 正常跳轉this.$router.push({path: url})}}}
}
</script>
用此種方法,當點擊同一菜單時,地址欄每次的變化都是從:http://localhost:8080/#/redirect?path=xxxxxx
?至?http://localhost:8080/#/xxxxxx
?參考文檔:Vue 項目重復點擊菜單刷新當前頁面 - 掘金 (juejin.cn)