vue 底部导航栏高亮。 ---使用$route.path 处理选项卡高亮 与 利用vue多次点击跳转的报错来实现多次点击回到顶部
最简单的方法,使用声明式导航的 active-class属性
<router-view></router-view>
<router-link to="/home" active-class="bgcolor" tag="li">menu</router-link>
<router-link to="/menu" active-class="bgcolor" tag="li">mine </router-link>
<router-link to="/mine" active-class="bgcolor" tag="li">home</router-link>
再定义对应的那个类
.bgcolor {
color: red;
background-color: pink;
}
即使刷新也不会出现高亮不对的情况

跳转的哪个,vue会自动给他加类
2021/1/13
================================================后面为年轻时造的方形轮子,忽略不计 =v=“ ===============================================
mounted() { this.footerHightLight(); //改变底部高亮 }, methods: { footerHightLight(path = null) { // console.log("当前路径名 :" + this.$route.path); //footer底部高亮问题,通过获取路由route.path的字符串后切片成数组,判断他在哪个页面 let pathList = this.$route.path.split("/"); let nowPathName = ""; let navVal = ["home", "commiunity", "more", "mine"]; if (path !== null) { pathList = [path]; for (const iterator of navVal) { if (pathList.includes(iterator)) { nowPathName = iterator; break; } } } else { for (const iterator of navVal) { if (pathList.includes(iterator)) { nowPathName = iterator; break; } } } // 上面为判断所在的页面是哪个 // console.log("处理后的变量的路劲" + nowPathName); //下面为通过refs获得dom面后进行样式操作 navVal.forEach((item)=>{ //每次点击跳转的时候初始化样式 this.$refs.[item].style.color = "black"; }) //改变激活那一栏的样式 this.$refs.[nowPathName].style.color = "white"; },
上面是通过route来高亮导航栏
上面个的思路是获取route的值,得到的是字符串,然后切片处理查找后根据路径来查找refs,改变其颜色
html里的写法
<footer> <div @click="routerClick('/home'), footerHightLight('home')" ref="home"> <i class="iconfont icon-home"></i> <p>主页</p> </div> <div @click="routerClick('/commiunity'), footerHightLight('commiunity')" ref="commiunity" > <i class="iconfont icon-more1"></i> <p>社区</p> </div> <div @click="routerClick('/more'), footerHightLight('more')" ref="more"> <i class="iconfont icon-icon-test"></i> <p>新闻</p> </div> <div @click="routerClick('/mine'), footerHightLight('mine')" ref="mine"> <i class="iconfont icon-user"></i> <p>我的</p> </div> </footer>
下面是多次点击报错【vue-router.esm.js?8c4f:1958 Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "路径"】
通过catch()来跳到页面顶部
routerClick(url) { //footer的页面跳转,多次点击报错通过catch来回到页面顶部 this.$router.push({ path: url }).catch(() => { let timer = null; let than = this; cancelAnimationFrame(timer); timer = requestAnimationFrame(function fn() { var oTop = document.body.scrollTop || than.$refs.main.scrollTop; if (oTop > 0) { than.$refs.main.scrollTo(0, oTop - 20); timer = requestAnimationFrame(fn); } else { cancelAnimationFrame(timer); } }); }); },
浙公网安备 33010602011771号