在Vue中實(shí)現(xiàn)隨hash改變響應(yīng)菜單高亮
情景
Vue+Element 實(shí)現(xiàn)管理頁面菜單欄,
點(diǎn)擊菜單時(shí) router 改變 hash 訪問不同子組件。
但是改變 hash 時(shí)菜單欄展開狀態(tài)和 highlight 并不會(huì)同步,
需要手動(dòng)實(shí)現(xiàn)。
Try Try See
第一反應(yīng)是通過 onhashchange 監(jiān)聽 hash 的變化,
講 location.hash.slice(2) 推給 menu 的 default-active 即可。
此時(shí)通過手動(dòng)輸入 url 或者前進(jìn)后退時(shí)均可正常加載對(duì)應(yīng)狀態(tài),但是通過組件中的 link 訪問時(shí),menu 的狀態(tài)沒有改變。
加入 alert 驗(yàn)證發(fā)現(xiàn)沒有觸發(fā) hashchange。
Why
Seafault 的解釋是
Vue-Router 底層調(diào)用的是 history.pushState查閱 MDN 發(fā)現(xiàn)
注意 pushState() 絕對(duì)不會(huì)觸發(fā) hashchange 事件,即使新的 URL 與舊的 URL 僅哈希不同也是如此。Solution
Vue-Router 的文檔中給出兩個(gè)方案
watch $route 對(duì)象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() }}
另外
原來的組件實(shí)例會(huì)被復(fù)用。因?yàn)閮蓚€(gè)路由都渲染同個(gè)組件,比起銷毀再創(chuàng)建,復(fù)用則顯得更加高效。不過,這也意味著組件的生命周期鉤子不會(huì)再被調(diào)用。
知識(shí)點(diǎn)擴(kuò)展
vue關(guān)于點(diǎn)擊菜單高亮與組件切換
有兩種
一種是 使用router-link 這種直接可以用router-link-active 來寫高亮樣式 組件在路由跳轉(zhuǎn)后 高亮依舊存在
一種是:is的應(yīng)用了 點(diǎn)擊觸發(fā)事件 事件改變currentView的值 可以直接改掉 :is 這個(gè)引入文件入口
<template> <div class='index'> <div class='headTop'></div> <div class='nav'> <img src='http://m.lshqa.cn/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'>場(chǎng)站</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 >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中實(shí)現(xiàn)隨hash改變響應(yīng)菜單高亮的文章就介紹到這了,更多相關(guān)vue 菜單高亮內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. python實(shí)現(xiàn)讀取類別頻數(shù)數(shù)據(jù)畫水平條形圖案例2. python中PyQuery庫用法分享3. python操作數(shù)據(jù)庫獲取結(jié)果之fetchone和fetchall的區(qū)別說明4. python將下載到本地m3u8視頻合成MP4的代碼詳解5. JavaScript實(shí)現(xiàn)組件化和模塊化方法詳解6. 使用css實(shí)現(xiàn)全兼容tooltip提示框7. python 爬取嗶哩嗶哩up主信息和投稿視頻8. Java 基于UDP協(xié)議實(shí)現(xiàn)消息發(fā)送9. CSS3實(shí)現(xiàn)動(dòng)態(tài)翻牌效果 仿百度貼吧3D翻牌一次動(dòng)畫特效10. Python編寫nmap掃描工具
