VueRouter的使用步骤5 + 2
1.下载 npm i vue - router@3.6.5
2.引入 import VueRouter from 'vue-router'
3.安装注册 Vue.use(VueRouter)
4.创建路由对象 const router = new VueRouter()
5.注入 new Vue({
render: h => h(App),
router
}).$mount('#app')
1.创建需要的组件(view目录),配置路由规则
2.配置导航,配置路由出口
配置导航
routes: [
{ path: '/find', component: find},
{ path: '/my', component: my},
{ path: '/friend', component: friend}
]
配置路由出口
1.用a标签
<div class="footer_wrap">
<a href="#/find">发现音乐</a>
<a href="#/my">我的</a>
<a href="#/friend">朋友</a>
</div>
2.用router-link代替a标签,可以实现高亮效果
<div class="footer_wrap">
<router-link to="/find">发现音乐</router-link>
<router-link to="/my">我的</router-link>
<router-link to="/friend">朋友</router-link>
</div>
在style中设置高亮颜色
模糊匹配和精确匹配的区别在于:如对'/find',如果是模糊匹配,那么访问'/find/a' 'find/b'时都显示高亮,而如果是精确匹配那只有在'/find'时才会显示高亮,访问后面两个路径时不会显示高亮。
/*模糊匹配*/
.router-link-active{
background-color: aquamarine;
}
/* 精确匹配 */
.router-link-exact-active{
background-color: aquamarine;
}
可以更改高亮的类名,语法为
linkActiveClass: 'high',
linkExactActiveClass: 'exactHigh'
两种传参方式
1.查询参数:比较适合有多种参数的情况
/*语法
*to="/path?参数名1=值&参数名2=值"
*获取:$route.query.参数名
*/
<router-link to="/find?a=1&b=2">发现音乐</router-link>
2.动态路由
routes: [
// 一下这一行,要是没有?表示传参数,加?表示可以没有参数
{ path: '/my/:words?', component: my, name: 'my' },
],
<router-link to="/my/params1">我的</router-link>
获取方式为:$route.params.参数名
两种路由跳转方式(this.$router.push)
1.通过路径跳转
this.$router.push({
path:'/find',
query:{
a:3,
b:4
}
})
this.$router.push({
path:'/find?a=3&b=4'
})
this.$router.push({
path:'my/params2'
})
2.通过路径名跳转
this.$router.push({
name:'find',
query:{
a:3,
b:4
},
})
this.$router.push({
name:'my',
params:{
words:'params2',
}
})
路由重定向和404
routes: [
{ path: '/', redirect: '/find' },
{ path: '*', component: notfound }
]