Vue Router_query、命名路由、params、props
1.路由的query参数
传递参数
跳转
跳转
接收参数:
$route.query.id
$route.query.title
2.命名路由
作用:可以简化路由的跳转。
如何使用:
- 给路由命名:
{
path:'/demo',
component:Demo,
children:[
{
path:'test',
component:Test,
children:[
{
name:'hello' //给路由命名
path:'welcome',
component:Hello,
}
]
}
]
}
2.简化跳转:
跳转
跳转
跳转
案例:
案例的样式基于bootstrap,在public\index.html里面引入即可。
src\components\Banner..vue
Vue Router Demo
src\pages\About.vue
我是About的内容
src\pages\Home.vue
Home组件内容
src\pages\News.vue
- news001
- news002
- news003
src\pages\Message.vue
-
{{m.title}}
src\pages\Detail.vue
- 消息编号:{{$route.query.id}}
- 消息标题:{{$route.query.title}}
src\App.vue
About
Home
src\router\index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router";
import About from "../pages/About.vue";
import Home from "../pages/Home.vue";
import Message from "../pages/Message.vue";
import News from "../pages/News.vue"
import Detail from "../pages/Detail.vue"
//创建并暴露一个路由器
export default new VueRouter({
routes:[
{
name:"guanyu",
path:"/About",
component:About
},
{
path:"/home",
component:Home,
children:[
{
path:"message",
component:Message,
children:[
{
name:"xiangqing",
path:"detail",
component:Detail
}
]
},
{
path:"news",
component:News
}
]
}
]
});
3.路由的params参数
①配置路由,声明接收params参数
{
path:'/home',
component:Home,
children:[
{
path:'news',
component:News
},
{
component:Message,
children:[
{
name:'xiangqing',
path:'detail/:id/:title', //使用占位符声明接收params参数
component:Detail
}
]
}
]
}
②传递参数
跳转
跳转
特别注意:路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置!
4.路由的props配置
作用:让路由组件更方便的收到参数
{
name:'xiangqing',
path:'detail/:id',
component:Detail,
//第一种写法:props值为对象,该对象中所有的key-value的组合最终都会通过props传给Detail组件
// props:{a:900}
//第二种写法:props值为布尔值,布尔值为true,则把路由收到的所有params参数通过props传给Detail组件
// props:true
//第三种写法:props值为函数,该函数返回的对象中每一组key-value都会通过props传给Detail组件
props(route){
return {
id:route.query.id,
title:route.query.title
}
}
}
修改上面案例的Message和Detail组件即可看到效果
src\pages\Message.vue
-
{{m.title}}
- 消息编号:{{id}}
- 消息标题:{{title}}
修改src\router\index.js里的如下代码即可
//创建并暴露一个路由器
export default new VueRouter({
routes:[
{
name:"guanyu",
path:"/About",
component:About
},
{
path:"/home",
component:Home,
children:[
{
path:"message",
component:Message,
children:[
{
name:"xiangqing",
//path:"detail/:id/:title",//params传参专用
path:"detail",
component:Detail,
//props的第一种写法,值为对象。该对象中的所有key-value都会以props的形式传给Detail组件。
//props:{a:1,b:"hello"},
//props的第二种写法,值为对象。若布尔值为真,就会把该路由组件收到的所有params参数以props的形式传给Detail组件
// props:true,//不能接收query参数
//props的第二种写法,值为函数。
props($route){
return {
id:$route.query.id,
title:$route.query.title
}
}
}
]
},
{
path:"news",
component:News
}
]
}
]
});