监听路由变化的方法
<template>
<div>
<ul>
<li v-for="(item,index) in menuList" :key="index" :class="{'active': isActive == index}" @click="handleClick(index)">
<router-link :to="item.path"> {{item.name}} </router-link>
</li>
</ul>
//或者 不用 router-link 通过 @click="handleClick(index, item.path)" 实现路由跳转
//<ul class="nj-container nav-list">
// <li v-for="(item,index) in menuList" :key="index" :class="{'active': isActive == index}" @click="handleClick(index, item.path)">
// {{item.name}}
// </li>
// </ul>
</div>
</template>
<script>
export default {
data() {
return {
isActive: 0,
menuList: [
{ name: "首页", path: "/index" },
{ name: "产品", path: "/product" },
{ name: "动态", path: "/news" },
{ name: "简介", path: "/info" },
{ name: "联系我们", path: "/contact" },
],
}
},
created() {
this.getUrl(); // 可以防止刷新的时候对应菜单不高亮显示 或 第一个高亮
},
methods: {
handleClick(index) {
this.isActive = index
},
//或者
//handleClick(index, path) {
//this.isActive = index;
//this.$router.push(path); //路由跳转
//},
getUrl() {
let path = this.$route.path; // 当前的路径
let index = this.menuList.findIndex(item => item.path === path); // 查找当前路由下的下标
this.isActive = index;
}
},
watch: {
'$route': 'getUrl' // 监听路由变化
}
}
</script>
<style lang="less" scoped>
li.active {
color: #fff;
background-color: #ff6750;
}
</style>
下方是我微信公众号的二维码,可以扫码关注以下,后期博文推送主要在公众号上面,有什么问题也可以通过公众号跟我发消息哦~