vue-router可以在切换时携带参数从A页面到B页面
由此可以实现两个页面之间的通信,vue-router目前可用路由方式如下
1.普通路由,没有携带任何参数
const router = new VueRouter({
routes: [
{ path: '/', component: Hello },
]
})
2.动态匹配路由
const router = new VueRouter({
routes: [
{ path: '/hello/:name', component: Hello}, //A.未开启props布尔模式
{ path: '/hello/:name', component: Hello, props: true }, //B.开启布尔模式
]
})
以上两种路由模式的异同之处如下所示
相同点:都可以在Hello组件中通过this.$route.params.name获取到路由参数,
不同点:B可以通过props直接获取name值,从而与this.$route解耦
具体写法如同父子组件传参一样
<template>
<span>{{name}}</span>
</template>
<script>
export default {
name: 'Hello',
props: ['name'],
mounted() {
console.log(this.name);
}
}
</script>
这里不用再通过this.$route.params.name获取name的值
这里B中没有动态路由匹配也没有问题即
const router = new VueRouter({
routes: [
{ path: '/hello', component: Hello, props: true }, //B.开启布尔模式
]
})
这样也是可以通过props获取到参数的
3.对象模式
对象模式不怎么常用,即两个页面通信值为一个静态对象时这个值可以通过路由来传递
const router = new VueRouter({
routes: [
{ path: '/static', component: Hello, props: { name: 'world' }}
]
})
此时获取方式与2中B的获取方式相同,应用场景不是很常见或者说比较狭小
4.函数模式
function setName(route){
const now = new Date().getTime();
return {
name: route.params.name + now;
}
}
const router = new VueRouter({
routes: [
{ path: '/hello/:name', component: Hello, props: setName},
]
})
以上简言之props有回调函数,参数为route对象,可以获取附带动态路由的参数,并进行加工处理
最终返回处理之后的值,才切换目标页面也同样需要有props,可以直接获取该值