动态路由的使用、导航守卫
在某一些情况下,一个页面的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 是 我 们 在 配 置 每 个 组 件 的 路 由 时 配 置 的 ‘ c o n s t r o u t e s = [ ] ‘ 这 个 数 组 中 的 各 个 路 由 , 那 个 路 由 处 于 活 跃 状 态 , 这 个 t h i s . route是我们在配置每个组件的路由时配置的`const routes=[]`这个数组中的各个路由,那个路由处于活跃状态,这个this. route是我们在配置每个组件的路由时配置的‘constroutes=[]‘这个数组中的各个路由,那个路由处于活跃状态,这个this.route获取的就是什么
在组件中获取变量值
方式一:计算属性
computed:{
userID(){
return this.$route.params.userID
}
}
这里的变量名是通过path:'/user/:userId',
这里冒号后面的变量名定义的变量名
方法二:直接在Mastach中获取
{{$route.params.userId}}
三、导航守卫
实现加载组件时更改页面的title
router.beforeEach((to,from,next)=>{
//从from跳转到to
document.title=to.meta.title
next()
})
router是beforeEach函数效果相当于每个组件中的each,参数分别有三个,to和from是两个route对象,页面从from跳转到to。next是一个函数,表示继续执行接下来的页面渲染,如果不调用这个,页面会停住。
我们可以在每一个路由配置是添加一个属性meta
{
path:'/about',
component:about,
meta:{title:'about'}
}
通过to.meta
来调用,meta中定义的数据。meta
元数据,意思是描述数据的数据
在源码中,router.beforeEach(to,from)函数是在组件加载前调用,还有一个后置钩子叫router.afterEach(to,from)函数,在组件加载完后调用。
其他的一些守卫
-
路由独享守卫
{ path:'news', component:news, meta:{title:'news'}, beforeEnter:(to,from,next)=>{ console.log('about beforeEnter'); next } }
beforeEnter
函数会在进入这个组件时被调用 -
组件内守卫 写在组件里面的
四、keep-alive
keep-alive
是vue内置的一个组件,可以使被包含的组件保留状态,或避免被重新渲染
如果<rooter-view>
包含在keep-alive
里面,所有路径匹配到的视图组件都会被缓存
<keep-alive><router-view></router-view></keep-alive>
因为存在<keep-alive>
所以在组件中会可以调用两个生命周期函数activated
和deactivated
,分别表示活跃和不活跃,当我们跳转到别的组件是,原来的组件就会从activated
变为deactivated
为了实现在跳回home时可以记录home中子组件的状态
使用了一个组件内守卫
beforeRouteLeave(to,from,next) {
console.log(from.path);
this.path=from.path;
next()
}
现在跳回home时可以记录home中子组件的状态
使用了一个组件内守卫
beforeRouteLeave(to,from,next) {
console.log(from.path);
this.path=from.path;
next()
}