简介
比如说,左侧有众多菜单栏,当点击一个菜单栏,进入一个页面,要保证左侧此页面对应的菜单栏 item 是高亮的
前置依赖
和 vue 搭配的路由一般使用 vue-router,可以 npm 拉和使用,然后 src/router/index.js 默认是写好的,可以看我之前文章,大概就是配置路由,然后让这个路由被项目使用:
// index.js 中的代码
import { createRouter, createWebHistory} from "vue-router"
const routes = [
{
// 路由 1
},
{
// 路由 2
},
]
const router = createRouter({
routes, // 路由路径哪些
history: createWebHistory(),
})
export default router
html 菜单 item
在某个应用组建页面,你需要做这种菜单依据定位到哪个 router 来进行高亮
<li>
<router-link :to="/xxx/yyy" :class="[activePath=='/xxx/yyy'?'style1':'style2']"> </router-link>
</li>
<!-- router-view 可能在下方什么地方显示 -->
下方 js 有 activePath
如果 activePath 是这个路径,那么就用 style1 的高亮样式,否则用 style2 样式
这里的路由 /xxx/yyy 在实际开发中往往是 js 中传过来的变量形式
js 监听路由变化
在同一个应用组件中的 js 区域有:
import {ref, watch} from "vue";
import {useRoute} from "vue";
const route = useRoute()
const activePath = ref(null)
// 监听路由的变化,有变化 newVal 中就会有最新的路由
watch(route, (newVal, oldVal) => {
console.log(newVal.path)
activePath.value = newVal.path
}, {immediate: true, deep: true});