This is App.vue File
<template>
<div id="app">
<main-header/>
<router-view/>
<main-footer/>
</div>
</template>
<script>
import MainHeader from './components/layouts/MainHeader'
import MainFooter from './components/layouts/MainFooter'
export default {
name: 'App',
components: {
'main-header': MainHeader,
'main-footer': MainFooter
}
}
</script>
Header.vue 文件是
<ul class="nav nav-pills" id="mainNav">
<li class="dropdown">
<a class="active" href="/">
Home
</a>
</li>
<li>
<a class="dropdown-item dropdown-toggle" href="/test1">
test1
</a>
</li>
<li>
<a class="dropdown-item dropdown-toggle" href="/test2">
test2
</a>
</li>
</ul>
我想为每个页面激活不同的"活动类"。 我不知道该怎么办
如果我单击"test2",活动类只需使用带有"test2"的标签进行维护 如何解决此问题?
你可以考虑使用 Vue-router 和active-class
prop
<ul class="nav nav-pills" id="mainNav">
<router-link to="/" tag="li" class="dropdown" active-class="active">Home</router-link>
<router-link to="/test1" tag="li" class="dropdown-item dropdown-toggle" active-class="active">Test1</router-link>
<router-link to="/test2" tag="li" class="dropdown-item dropdown-toggle" active-class="active">Test2</router-link>
</ul>
另一个幼稚的解决方案是 检查window.location.href
,但涵盖所有可能的情况并不简单。
<ul class="nav nav-pills" id="mainNav">
<li class="dropdown">
<a class="active" href="/">
Home
</a>
</li>
<li>
<a class="dropdown-item dropdown-toggle" href="/test1" :class="getClass('/test1')">
test1
</a>
</li>
<li>
<a class="dropdown-item dropdown-toggle" href="/test2" :class="getClass('/test2')">
test2
</a>
</li>
</ul>
<script>
export default {
methods: {
getClass(url) {
if (window.location.href.includes(url)) {
return "active"
}
return ""
}
}
}
</script>