1. 程式人生 > 其它 >vue 使用:class切換高亮 點選路由跳轉 上個元件的點選事件儲存的引數 在下一次重複進入這個元件的時候 預設值都已經還原了 得通過路由跳轉的時候 把上個元件的狀態通過路由儲存下來 通過下一次進入這個元件的時候 獲取路由 渲染當前頁面的:class 進行高亮

vue 使用:class切換高亮 點選路由跳轉 上個元件的點選事件儲存的引數 在下一次重複進入這個元件的時候 預設值都已經還原了 得通過路由跳轉的時候 把上個元件的狀態通過路由儲存下來 通過下一次進入這個元件的時候 獲取路由 渲染當前頁面的:class 進行高亮

第2種方式 通過元件庫屬性直接操作
      <div class="nav">
        <router-link
          :to="item.path"
          v-for="(item, index) in navData"
          :key="index"
        >{{ item.name }}11</router-link>
      </div>

    .router-link-active {
      background-color: rgba(68, 142, 246, 1);
      color: #ffffff;
    }
第1種方式
<template> <div class="header"> <div class="box"></div> <div class="content"> <router-link to="/home1" active-class="active" ><span>博之億</span></router-link> <div class="nav"> <ul> <!-- @click="$router.push({ path: item.path }), (active = index)" --> <!-- :class="{ nav_index: active === index }" --> <!-- 給當前li加樣式 給其他li去樣式--> <li v-for="(item, index) in navData" :key="item.name" @click="test(item, index)" :class="{ nav_index: active == item.name }" > {{ item.name }} </li> </ul> </div> </div> </div> </template> <script> export default { data () { return { navData: [ { name: "首頁1", path: "/home1" }, { name: "人才網校", path: "/home2" }, { name: "商務合作", path: "/home3" }, { name: "關於我們", path: "/home4" }, { name: "新聞中心", path: "/home5" }, { name: "招賢納士", path: "/home6" }, ], //預設渲染第1個 active: "首頁1", }; }, watch: { "$route.path": { handler(val) { console.log(this.$route.query.name,"選單:", val); // this.selectTag = val; //val是路由跳轉的path this.active = this.$route.query.name }, immediate: true //立即執行 } }, methods: { test(item, index){ this.$router.push({ path: item.path, query: {name: item.name}}); var obj = JSON.stringify(item.name) let objClone = JSON.parse(obj) this.active = objClone console.log(this.active,"我正在測試 active",index,"11",this.active == index,"22",item.name) } } }; </script> <style lang="less"> .header { .nav { float: right; ul { width: 600px; height: 80px; line-height: 88px; margin: 0 auto; font-size: 18px; display: flex; justify-content: space-between; li { width: 100px; height: 80px; float: left; text-align: center; line-height: 80px; font-size: 18px; color: #000; cursor: pointer; // background: #d14e4e; } .nav_index { width: 100px; height: 80px; background-color: rgba(68, 142, 246, 1); color: #ffffff; } } } } </style>