目录:
初始代码如下:
App.vue:
<template>
<div id="app">
<router-link to="/">首页</router-link>
<router-link to="/about">关于</router-link>
<router-view />
</div>
</template>
<script>
export default {
name: 'App',
}
</script>
<style>
.active {
color: #f00
}
</style>
views-->Home.vue:
<template>
<div>
首页内容
</div>
</template>
<script>
export default {
name: 'Home',
}
</script>
<style>
</style>
views-->About.vue:
<template>
<div>
关于我们内容
</div>
</template>
<script>
export default {
name: 'About',
}
</script>
<style>
</style>
main.js:
import Vue from 'vue'
import router from './router'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App),
}).$mount('#app')
router-->index.js:
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
component: Home
},
{
path: '/about',
component: About
},
]
const router = new VueRouter({
routes,
mode: 'history',
linkActiveClass: 'active'
})
export default router
初始效果:
产生该问题的原因:
routes中的path第一个为'/',第二个为'/about',两个均以'/'开头,而默认情况下linkActiveClass为模糊匹配,所以两个都会匹配到高亮显示。
解决:
将第一个路由改为'/home',如果想要'/'根目录打开即加载home页面内容,则增加一个重定向redirect:
const routes = [
{
path: '',
redirect: '/home'
},
{
path: '/home',
component: Home
},
...
]
再将App.vue中“首页”’router-link对应的路由地址修改为'/home':
<router-link to="/home">首页</router-link>
修改后运行效果:
1. 未添加重定向redirect路由:
2. 添加了重定向redirect路由: