# 路由的配置
# 使用params 参数
- 要先配置路由,声明接收params参数
{
path:'/home',
component:Home,
children:[
{
path:'news',
component:News
},
{
component:Message,
children:[
{
name:'xiangqing',
path:'detail/:id/:title', //使用占位符声明接收params参数
component:Detail
}
]
}
]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
- 传递参数
<!-- 跳转并携带params参数,to的字符串写法 -->
<router-link :to="/home/message/detail/666/你好">跳转</router-link>
<!-- 跳转并携带params参数,to的对象写法 -->
<router-link
:to="{
name:'xiangqing',
params:{
id:666,
title:'你好'
}
}"
>跳转</router-link>
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 路由的 props 配置
props作用:让路由组件更方便的收到参数
{
name:'xiangqing',
path:'detail', //query参数传递形式
path:'detail/:id/:id2', //params参数传递形式
component:Detail,
//第一种写法:props值为对象,该对象中所有的key-value的组合最终都会通过props传给Detail组件(固定传值)
// props:{a:900}
//第二种写法:props值为布尔值,为true时,则把路由收到的所有params参数通过props传给Detail组件
// props:true
//第三种写法:props值为函数,该函数返回的对象中每一组key-value都会通过props传给Detail组件。针对query参数传递形式
props($route){
return {
id: $route.query.id,
title: $route.query.title
}
}
// props的第三种写法,值为函数
props(params) { // 这里可以使用解构赋值
return {
id: params.id,
title: params.title,
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
页面组件要设置接收props参数名
export default {
name:'Detail',
props:['id','title']
}
1
2
3
4
2
3
4
# 编程式路由导航
作用:不借助<router-link>实现路由跳转,让路由跳转更加灵活
this.$router.push({}) 内传的对象与<router-link>中的to相同
this.$router.replace({}) this.$router.forward() 前进
this.$router.back() 后退
this.$router.go(n) 可前进也可后退,n为正数前进n,为负数后退
this.$router.push({
name:'xiangqing',
params:{
id:xxx,
title:xxx
}
})
this.$router.replace({
name:'xiangqing',
query:{
id:xxx,
title:xxx
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 缓存路由组件
// 缓存一个路由组件
<keep-alive include="News"> // include中写想要缓存的组件名,不写表示全部缓存
<router-view></router-view>
</keep-alive>
// 缓存多个路由组件
<keep-alive :include="['News','Message']">
<router-view></router-view>
</keep-alive>
include 和exclude是组件名,不是路由表名
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# activated deactivated
activated(){
console.log('组件被激活了')
this.timer = setInterval(() => {
this.opacity -= 0.01
if(this.opacity <= 0) this.opacity = 1
},16)
},
deactivated(){
console.log('组件失活')
clearInterval(this.timer)
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
← 12.VueRouter 14.路由守卫 →