場景:
vue實現導航欄,二級導航欄跳轉到相同頁面,通過參數來實現到該頁面后,根據參數來滾動到對應到位置
網上的解決方法:
通常情況下我們喜歡設置keepAlive 包裹 router-view
<div id="app"> <keep-alive> <router-view></router-view> </keep-alive> </div>
同時在created 中觸發請求,在路由參數不同的情況下並不會執行對應的操作。
解決方法:
1、給 router-view 設置 key 屬性為路由的完整路徑
<keep-alive> <router-view :key="$route.fullPath"></router-view> </keep-alive>
這種方法我覺得應該是一勞永逸的方法,可能對性能造成一定損耗。不適用於一個tab切換路由並加載列表的組件,會造成頁面白屏,dev模式不會自動刷新,是個坑
2、官方給出的方法是通過 watch 監聽路由變化,做判斷路由路徑然后調用響應的方法
watch: { '$route'() { if (this.$route.path === 'test') { this.test(); } } } watch: { 'id': { handler: 'test', //調用方法 immediate: true, //進入立即執行一次 } },
這兩種方法推薦第一種,第二種需要先對參數id進行賦值
3、通過組件導航守衛來設置對應的meta 屬性
beforeRouteEnter: (to, from, next) = > { // 寫在當前組件 to.meta.keepAlive = false next() }, beforeRouteLeave: (to, from, next) = > { //寫在前一個組件 to.meta.keepAlive = false next() },
我的解決方法
網上的方法都是試了下,還是沒有效果,於是開始自己瞎鼓搗,還真的解決了,所以來記錄一下,這個方法還是比較笨拙的,如果有更好的解決方法,希望告知,🙏🙏
1.首先在路由添加參數
// 關於我們 { path: '/aboutusBase', component: AboutUs, redirect: '/aboutus', children: [ { path: '/aboutus/:index', components: { default: Banner, founder: Founder, hall_of_fame: HallOfFame, team: Team, }, name: 'AboutUsLink' } ] },
2.跳轉路由
this.$router.push({ name: "AboutUsLink", params: { index: list_index } //list_index為可變參數 });
3.在你需要跳轉的頁面設置路由監聽
watch: { // 利用watch方法檢測路由變化: $route: function(to, from) { if (to.path !== from.path) { this.selected_index = to.params.index; // 獲取參數 this.getAnimateScroll(); // 滾動方法 } } },
⚠️在接收參數的時候,一定要對參數進行過濾判斷