需求:點擊左菜單刷新當前路由頁面。
通過查詢資料,找到兩種實現方式
第1種:在路由后面加上時間戳,通過不斷改變 url 的 query 來觸發 view 的變化,監聽側邊欄每個 link 的 click 事件,每次點擊都給 router push 一個不一樣的 query 來確保會重新刷新 view。
// 路徑地址: src\views\layout\components\Sidebar\Link.vue export default { props: { to: { type: String, required: true } }, methods: { testClick(url) { sessionStorage.setItem('defaultActive', JSON.stringify(url)) // 通過時間戳實現菜單刷新 this.$router.push({ path: url, query: { t: +new Date() // 保證每次點擊路由的query項都是不一樣的,確保會重新刷新view } }) }, linkProps(url) { return { is: 'div' } } } }
存在問題:點擊后路由后面都加了一串時間戳導致累贅,另外雖然模擬了刷新了當前頁面,但實際並沒有重新請求接口
第2種,花褲衩提供的方法,創建一個空的Redirect頁面,通過判斷當前點擊的菜單路由和當前的路由是否一致,一致的時候,會先跳轉到專門 Redirect 的頁面,然后將路由重定向到我想去的頁面,這樣就起到了刷新的效果了。展示方式如圖1
// 1. src\router\index.js 首先添加路由 { path: '/redirect', // 重定向路由 // component: () => import('@/views/layout/components/Sidebar/redirect'), hidden: true component: Layout, hidden: true, children: [{ path: '', component: () => import('@/views/layout/components/Sidebar/redirect') }] }, // 2. src\views\layout\components\Sidebar\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> // 3. src\views\layout\components\Sidebar\Link.vue 菜單頁面添加如下代碼 進行跳轉 <template> <!-- eslint-disable vue/require-component-is --> <component v-bind="linkProps(to)" @click="testClick(to)"> <slot/> </component> </template> <script> // import { isExternal } from '@/utils/validate' export default { props: { to: { type: String, required: true } }, methods: { testClick(url) { // 通過重定向空白路由頁面實現當前菜單刷新 if (JSON.parse(sessionStorage.getItem('defaultActive')) === url) { // 點擊的是當前路由 手動重定向頁面到 '/redirect' 頁面 sessionStorage.setItem('defaultActive', JSON.stringify(url)) const fullPath = encodeURI(url) this.$router.replace({ path: '/redirect', query: { path: encodeURI(fullPath) } }) } else { sessionStorage.setItem('defaultActive', JSON.stringify(url)) // 正常跳轉 this.$router.push({ path: url }) } }, linkProps(url) { return { is: 'div' } } } } </script>