在Vue中實(shí)現(xiàn)隨hash改變響應(yīng)菜單高亮
情景
Vue+Element 實(shí)現(xiàn)管理頁面菜單欄,
點(diǎn)擊菜單時(shí) router 改變 hash 訪問不同子組件。
但是改變 hash 時(shí)菜單欄展開狀態(tài)和 highlight 并不會同步,
需要手動實(shí)現(xiàn)。
Try Try See
第一反應(yīng)是通過 onhashchange 監(jiān)聽 hash 的變化,
講 location.hash.slice(2) 推給 menu 的 default-active 即可。
此時(shí)通過手動輸入 url 或者前進(jìn)后退時(shí)均可正常加載對應(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() 絕對不會觸發(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() }}
另外
原來的組件實(shí)例會被復(fù)用。因?yàn)閮蓚€路由都渲染同個組件,比起銷毀再創(chuàng)建,復(fù)用則顯得更加高效。不過,這也意味著組件的生命周期鉤子不會再被調(diào)用。
知識點(diǎn)擴(kuò)展
vue關(guān)于點(diǎn)擊菜單高亮與組件切換
有兩種
一種是 使用router-link 這種直接可以用router-link-active 來寫高亮樣式 組件在路由跳轉(zhuǎn)后 高亮依舊存在
一種是:is的應(yīng)用了 點(diǎn)擊觸發(fā)事件 事件改變currentView的值 可以直接改掉 :is 這個引入文件入口
<template> <div class='index'> <div class='headTop'></div> <div class='nav'> <img src='http://www.cgvv.com.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'>場站</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)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 利用CSS3新特性創(chuàng)建透明邊框三角2. IntelliJ IDEA導(dǎo)入jar包的方法3. WML語言的基本情況4. Python collections模塊的使用方法5. 如何通過vscode運(yùn)行調(diào)試javascript代碼6. AJAX實(shí)現(xiàn)數(shù)據(jù)的增刪改查操作詳解【java后臺】7. ajax post下載flask文件流以及中文文件名問題8. 使用css實(shí)現(xiàn)全兼容tooltip提示框9. python dict如何定義10. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能
