大家好,欢迎来到IT知识分享网。
params 参数,其实就是把参数写在路由地址上
details:id:titie这就是params参数
在 Vue入门032- 路由传递参数(query参数)的基础上修下router/index.js文件。改成params参数传递方式
router/index.js
// 该文件专门用于创建整个应用的路由器 import VueRouter from 'vue-router' //引入组件 import About from '../pages/About' import Home from '../pages/Home' import News from '../pages/News' import Message from '../pages/Message' import Detail from '../pages/Detail' //创建并暴露一个路由器 export default new VueRouter({ routes:[ { name:'guanyu', path:'/about', component:About }, { path:'/home', component:Home, children:[ { path:'news', component:News, }, { path:'message', component:Message, children:[ { name:'xiangqing', path:'detail/:id/:title', component:Detail, } ] } ] } ] })
关键代码 31行 name:’xiangqing’,
路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置!
关键代码 32行 path:’detail/:id/:title’,
:id 理解为占位符
:title 理解为占位符
Message.vue 组件
<template> <div> <ul> <li v-for="m in messageList" :key="m.id"> <!-- 跳转路由并携带params参数,to的字符串写法 --> <!-- <router-link :to="`/home/message/detail/${m.id}/${m.title}`">{{m.title}}</router-link> --> <!-- 跳转路由并携带params参数,to的对象写法 --> <router-link :to="{ name:'xiangqing', params:{ id:m.id, title:m.title } }"> {{m.title}} </router-link> </li> </ul> <hr> <router-view></router-view> </div> </template> <script> export default { name:'Message', data() { return { messageList:[ {id:'001',title:'消息001'}, {id:'002',title:'消息002'}, {id:'003',title:'消息003'} ] } }, } </script>
跳转路由并携带params参数,to的字符串写法
<router-link :to="`/home/message/detail/${m.id}/${m.title}`">{{m.title}}</router-link>
跳转路由并携带params参数,to的对象写法
<router-link :to="{ name:'xiangqing', params:{ id:m.id, title:m.title } }"> {{m.title}} </router-link>
Detail.vue 组件
<template> <ul> <li>消息编号:{{$route.params.id}}</li> <li>消息标题:{{$route.params.title}}</li> </ul> </template> <script> export default { name:'Detail', mounted() { // console.log(this.$route) }, } </script>
接收参数
{{$route.params.id}}
{{$route.params.title}}
路由的params参数总结
1. 配置路由,声明接收params参数
{ path:'/home', component:Home, children:[ { path:'news', component:News }, { component:Message, children:[ { name:'xiangqing', path:'detail/:id/:title', //使用占位符声明接收params参数 component:Detail } ] } ] }
2.传递参数
跳转并携带params参数,to的字符串写法
<router-link :to="/home/message/detail/666/你好">跳转</router-link>
跳转并携带params参数,to的对象写法
<router-link :to="{ name:'xiangqing', params:{ id:666, title:'你好' } }" >跳转</router-link>
特别注意:路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置!
3. 接收参数:
$route.params.id $route.params.title
代码摘录于尚硅谷Vue学习课件
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/145994.html