动态路由的使用、导航守卫
在某一些情况下,一个页面的path可能是不确定的
比如进入用户界面时,url可能是/user/jane这样,希望除了有/user外还有用户的id
一、动态url
- 首先我们按照原本的方式创造一个user.vue
<template>
<div>
<h2>用户界面</h2>
<p>hello world</p>
</div>
</template>
<script>
export default {
name:'user'
}
</script>
<style>
</style>
- 把这个组件链接到index.js中,给他配置路由
{
path:'/user/:userId',
component:user
}
这里的/:userId
是指这后面会跟一个变量
- 在to属性中指明路径
<router-link :to="`/user/${userid}`" tag="button">我的</router-link>
这里 to属性有两种写法:
1、用字符串拼接的方式:to="'/user/'+userid"
2、用ES6的模板的方式(如上文中代码所示)
二、在组件中获取这个变量的值
this.KaTeX parse error: Expected 'EOF', got '&' at position 6: route&̲&this.router区别
this.$router实际上拿到的是在index.js中安装的插件:Vue.use(VueRouter)
用在比如要用代码跳转组件时:this.$router.push('/home')
this. r o u t e 是 我 们 在 配 置