根据案例来学习是最好的学习方法,能够将所学的知识运用到案例中
练中学,学中练
那我们就话不多说就来学习一下路由中是如何传参的!
书写方法一:
{{m.title}}
其中?后面的id=${m.id}&title=${m.title}就是可以传递给网页的参数,如图:
书写方法二:(更推荐)
{{m.title}}
本案例中的路由是Detail.vue,它里面的代码如下:
- 消息编号:{{$route.query.id}}
- 消息标题:{{$route.query.title}}
✨注意:this.$route可以得到Detail.vue这个组件相关的配置信息。
使用方法如下:
Step1:
{
path:'/demo',
component:Demo,
children:[
{
path:'test',
component:Test,
children:[
{
name:'hello' //给路由命名
path:'welcome',
component:Hello,
}
]
}
]
}
Step2:
跳转 //to 后面写的是路径
跳转 //这里的to前面需要加冒号:
跳转
使用方法如下:
Step1:配置路由,声明接收params参数
{
path:'/home',
component:Home,
children:[
{
path:'news',
component:News
},
{
component:Message,
children:[
{
name:'xiangqing',
path:'detail/:id/:title', //使用占位符声明接收params参数
component:Detail
}
]
}
]
}
Step2:传递参数
跳转
跳转
作用:可以了解路由组件Detail.vue是如何读取它的参数的,让路由组件更方便的收到参数。
//在路由Deatil.vue中这么写
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',
component: Detail,
//props的第一种写法,值为对象,该对象中的所有key-value都会以props的形式传给Detail组件。(这样的话数据都是死的)
// props:{a:1,b:'hello'}
//props的第二种写法,值为布尔值,若布尔值为真,就会把该路由组件收到的所有params参数,以props的形式传给Detail组件。
// props:true
//props的第三种写法,值为函数--这种最强大
props($route) { //$route是回调函数
return {
// id:'666',title:'你好啊',这样写的话就会把数据写死了
id: $route.query.id,
title: $route.query.title,
a: 1,
b: 'hello'
}
}
}]
}
]
}
]
})
push
和replace
,push
是追加历史记录,replace
是替换当前记录。路由跳转时候默认为push。
在Home.vue中写入replace
Home组件内容
如下图理解,当我们点击返回按钮是会回到8080/#/about
返回到about这个页面
以上内容就是关于路由在传参过程中的理解与作用!
~ENDING~