Vue如何使得导航栏文字光标如何与内容同步
效果演示:
当我们点击上方链接的时候,这个光标会随着我们的点击,在不同的地方发生变化。
项目结构
这是一个标准的vue项目的结构。
完整代码:
这个是上方导航栏的组件代码。
NavBar.vue
<template>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<router-link class="navbar-brand" :to="{name: 'home'}">King Of Bots</router-link>
<div class="collapse navbar-collapse" id="navbarText">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<router-link :class="route_name == 'pk_index' ? 'nav-link active' : 'nav-link' " :to="{name: 'pk_index'}">对战</router-link>
</li>
<li class="nav-item">
<router-link :class="route_name == 'record_index' ? 'nav-link active' : 'nav-link' " :to="{name: 'record_index'}">对局列表</router-link>
</li>
<li class="nav-item">
<router-link :class="route_name == 'ranklist_index' ? 'nav-link active' : 'nav-link' " :to="{name: 'ranklist_index'}">排行榜</router-link>
</li>
</ul>
<ul class="navbar-nav">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
极客李华
</a>
<ul class="dropdown-menu">
<router-link class="dropdown-item" :to="{name: 'user_bot_index'}">我的Bot</router-link>
<li>
<hr class="dropdown-divider">
</li>
<li><a class="dropdown-item" href="#">退出</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
</template>
<script>
import {useRoute} from 'vue-router'
import {computed} from 'vue'
export default{
setup(){
const route = useRoute();
// computed可以计算当前的route是哪个 并返回它的名字
let route_name = computed(() => route.name)
return {
route_name
}
}
}
</script>
<style>
</style>
index.js
import { createRouter, createWebHistory } from 'vue-router'
import PkIndexView from '../views/pk/PkIndexView'
import RecordindexView from '../views/record/RecordindexView'
import RanklistindexView from '../views/ranklist/RanklistindexView'
import UserBotindexView from '../views/user/bot/UserBotindexView'
import NotFound from '../views/error/NotFound'
const routes = [
{
path: "/",
name: "home",
redirect: "/pk/"
},
{
path: "/pk/",
name: "pk_index",
component: PkIndexView,
},
{
path: "/record/",
name: "record_index",
component: RecordindexView,
},
{
path: "/ranklist/",
name: "ranklist_index",
component: RanklistindexView,
},
{
path: "/user/bot/",
name: "user_bot_index",
component: UserBotindexView,
},
{
path: "/404/",
name: "404",
component: NotFound,
},
{
path: "/:catchAll(.*)",
redirect: "/404/"
},
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
提取代码讲解
computed函数可以时时的获取当前的route的名字,具体写法就是下面的样子,然后返回每次的route的名字。
<script>
import {useRoute} from 'vue-router'
import {computed} from 'vue'
export default{
setup(){
const route = useRoute();
// computed可以计算当前的route是哪个 并返回它的名字
let route_name = computed(() => route.name)
return {
route_name
}
}
}
</script>
<style>
让这里的三元表达式获取到之后,进行判断,然后如果当前的这个标签是当前网页在运行的,那么就让这个样式里面再加上的一个active。
<router-link :class="route_name == 'pk_index' ? 'nav-link active' : 'nav-link' " :to="{name: 'pk_index'}">对战</router-link>