命名路由
-
作用:可以简化路由的跳转
-
如何使用:给路由命名
{ path:'/demo', component:Demo, children:[ { path:'test', component:Test, children:[ { name:'hello' //给路由命名 path:'welcome', component:Hello, } ] } ] }
简化跳转:简化之前需要写完整的路径如果路径较长则不容易被观察 简化之后可以直接通过路由的名字进行跳转便于维护和观察
<!--简化前,需要写完整的路径 --> <router-link to="/demo/test/welcome">跳转</router-link> <!--简化后,直接通过名字跳转 --> <router-link :to="{name:'hello'}">跳转</router-link> <!--简化写法配合传递参数 --> <router-link :to="{ name:'hello', query:{ id:666, title:'你好' } }" >跳转</router-link>
路由的参数传递
-
路由的query参数
传递参数 通过query对象方式传递 或者通过url字符串方式传递<!-- 跳转并携带query参数,to的字符串写法 --> <router-link :to="/home/message/detail?id=666&title=你好">跳转</router-link> <!-- 跳转并携带query参数,to的对象写法 --> <router-link :to="{ path:'/home/message/detail', query:{ id:666, title:'你好' } }" >跳转</router-link>
接收参数:$route.query.xxx
<template> <div> {{$route.query.id}} {{$route.query.title}} </div> </template>
-
路由的params参数
-
配置路由,声明接收params参数 ( 使用占位符声明接收params参数 )
{ path:'/home', component:Home, children:[ { path:'news', component:News }, { component:Message, children:[ { name:'xiangqing', path:'detail/:id/:title', //使用占位符声明接收params参数 component:Detail } ] } ] }
-
传递参数 通过params对象传递参数 或者通过url字符串方式传递
<!-- 跳转并携带params参数,to的字符串写法 --> <router-link :to="/home/message/detail/666/你好">跳转</router-link> <!-- 跳转并携带params参数,to的对象写法 --> <router-link :to="{ name:'xiangqing', params:{ id:666, title:'你好' } }" >跳转</router-link>
-
接收参数: $route.params.xxx
<template> <div> {{$route.params.id}} {{$route.params.title}} </div> </template>
-
特别注意:路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置!