Vue 路由传参
query
传参
- 字符串
<router-link :to="`/course/front?text=${text}`" active-class="active"> 前端 </router-link>
- 对象
<router-link :to="{ path: '/course/front', query: { text: text } }" active-class="active" > 前端 </router-link>
- 获取参数
this.$route.query.text
params
传参
- 路由器声明
params
传参
{
name: 'qianduan',
path: 'front/:text', //字符串形式传参时需加占位符告知路由器,此时是参数
component: Front,
},
- 字符串
<router-link :to="`/course/front/${text}`" active-class="active"> 前端 </router-link>
- 对象
<router-link :to="{ name: 'qianduan', params: { text: text } }" active-class="active" > 前端 </router-link>
- 获取
this.$route.params.text
注意
-
- 字符串形式传参时需加占位符告知路由器, 在路径后面是参数
path
对应的是query
属性,name
对应的是params
属性
replace
-
删除路由之前的历史记录
<router-link replace to="/course/back" active-class="active"> 后端 </router-link>
编程式路由导航
-
为什么要用编程式导航
- 当导航跳转不使用声明式跳转时(如:button标签)
- 不通过事件触发路由跳转
编程式导航
push
写法
# method方法中方法
toFront() {
this.$router.push({
name: "qianduan",
params: {
text: this.text,
},
});
},
replace
写法
#method方法中方法
toFront() {
this.$router.replace({
name: "qianduan",
params: {
text: this.text,
},
});
},
- 路由的前进后退
this.$router.forward() //前进
this.$router.back() //后退
this.$router.go() //前进:正数1、2 或者后退:负数-1、-2
全局前置路由【重要】
作用
-
对路由组件进行权限控制
配置
{
path: 'front',
component: Front,
meta: { isAuth: true },
},
{
path: 'back',
component: Back,
meta: { isAuth: true },
},
router.beforeEach((to, from, next) => {
if (to.meta.isAuth) {
if (localStorage.getItem('isShow' === '1')) {
next();
} else {
alert('暂无权限观看');
}
} else {
next();
}
});