在Vue中實現(xiàn)隨hash改變響應(yīng)菜單高亮
情景
Vue+Element 實現(xiàn)管理頁面菜單欄,
點擊菜單時 router 改變 hash 訪問不同子組件。
但是改變 hash 時菜單欄展開狀態(tài)和 highlight 并不會同步,
需要手動實現(xiàn)。
Try Try See
第一反應(yīng)是通過 onhashchange 監(jiān)聽 hash 的變化,
講 location.hash.slice
(2) 推給 menu 的 default-active
即可。
此時通過手動輸入 url 或者前進(jìn)后退時均可正常加載對應(yīng)狀態(tài),但是通過組件中的 link 訪問時,menu 的狀態(tài)沒有改變。
加入 alert 驗證發(fā)現(xiàn)沒有觸發(fā) hashchange。
Why
Seafault 的解釋是
- Vue-Router 底層調(diào)用的是 history.pushState
查閱 MDN 發(fā)現(xiàn)
- 注意 pushState() 絕對不會觸發(fā) hashchange 事件,即使新的 URL 與舊的 URL 僅哈希不同也是如此。
Solution
Vue-Router 的文檔中給出兩個方案
watch $route 對象 const User = { template: '...', watch: { $route(to, from) { // react to route changes... } } }
使用 beforeRouteUpdate
const User = { template: '...', beforeRouteUpdate(to, from, next) { // react to route changes... // don't forget to call next() } }
另外
原來的組件實例會被復(fù)用。因為兩個路由都渲染同個組件,比起銷毀再創(chuàng)建,復(fù)用則顯得更加高效。不過,這也意味著組件的生命周期鉤子不會再被調(diào)用。
知識點擴展
vue關(guān)于點擊菜單高亮與組件切換
有兩種
一種是 使用router-link 這種直接可以用router-link-active 來寫高亮樣式 組件在路由跳轉(zhuǎn)后 高亮依舊存在
一種是:is的應(yīng)用了 點擊觸發(fā)事件 事件改變currentView的值 可以直接改掉 :is 這個引入文件入口
<template> <div class="index"> <div class="headTop"></div> <div class="nav"> <img src="../assets/img/logo.png" alt=""> <el-row :gutter="20"> <el-col :span="3" @click.native="tabChange('FirstScreen')" ><div class="grid-content bg-purple">首頁</div></el-col> <el-col :span="3" @click.native="tabChange('pagetwo')"><div class="grid-content bg-purple">場站</div></el-col> <el-col :span="3" @click.native="tabChange('pagethree')" ><div class="grid-content bg-purple">訂艙</div></el-col> </el-row> </div> <div :is="currentView"></div> <!-- <div class="aaa" >asdasd</div> --> </div> </template> <script> import FirstScreen from '../views/containers/FirstScreen' import pagetwo from '../views/containers/pagetwo' import pagethree from '../views/containers/pagethree' export default { name: 'index', components:{ FirstScreen, pagetwo, pagethree }, data () { return { FirstScreen: 'FirstScreen', pagetwo: 'pagetwo', pagethree: 'pagethree', currentView: 'FirstScreen',//組建切換 activeIndex: '1', activeIndex2: '1', } }, computed:{ }, created(){ }, methods:{ tabChange(tabItem) { this.currentView = tabItem; console.log(this.currentView); } } } </script>
到此這篇關(guān)于在Vue中實現(xiàn)隨hash改變響應(yīng)菜單高亮的文章就介紹到這了,更多相關(guān)vue 菜單高亮內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue項目實現(xiàn)表單登錄頁保存賬號和密碼到cookie功能
這篇文章主要介紹了vue項目實現(xiàn)表單登錄頁保存賬號和密碼到cookie功能,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-08-08