<template>
<div>
<nav>
<router-link to="/home" :class="{ active: isActive('/home') }">Home</router-link> |
<router-link to="/about" :class="{ active: isActive('/about') }">About</router-link>
</nav>
<router-view></router-view>
</div>
</template>
<script>
export default {
data() {
return {
currentPath: this.$route.path
};
},
methods: {
isActive(path) {
return this.$route.path === path;
}
},
watch: {
$route(to) {
this.currentPath = to.path;
}
}
};
</script>
<style>
.active {
font-weight: bold;
color: red;
}
</style>
模板部分 (<template>):
router-link 组件来创建导航链接。router-link 都绑定了一个动态类 :class="{ active: isActive('/path') }",用于根据当前路径动态添加 active 类。脚本部分 (<script>):
isActive 方法,用于检查当前路由路径是否与传入的路径匹配。watch 监听 $route 的变化,以确保 currentPath 始终是最新的路径。样式部分 (<style>):
.active 类的样式,当某个链接被激活时,应用这些样式(例如加粗和红色字体)。上一篇:vue3 addroute
下一篇:vue2钩子函数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站