1. router-link传参
父组件:使用<router-link to="/跳转的路径/传递的参数"></router-link>
例如:<router-link to="/a/123"></router-link>
子组件接收:this.$route.params.num
来接收传递过来的参数
mounted(){
this.num=this.$route.params.num
}
路由配置:{path:‘/a/num’,name:A,component:A}
地址栏显示的:http://localhost:8080/#/a/123
2. 使用this.$router.push实现路由传参
父组件:绑定点击事件,编写跳转代码
<button @click="goGame(Math.floor(Math.random() * 999))">去游戏</button>
goGame (id) {
this.$router.push({
path: `/game/${id}`
})
},
路由:
{
path: '/game/:id',
name: 'game',
component: Game
},
子组件:
<div>
<h1>游戏{{id}}</h1>
</div>
data () {
return {
id: ''
}
},
mounted () {
this.id = this.$route.params.id
}
3. 通过路由属性的name匹配路由,在根据params传参
父组件
<button @click="goSheep">去羊村</button>
goSheep () {
this.$router.push({
name: 'sheep',
params: {
sheepName: '喜羊羊'
}
})
}
路由:
{
path: '/sheep',
name: 'sheep',
component: Sheep
},
子组件:
<div>
<h1>我是DJ{{name}}</h1>
</div>
data () {
return {
name: ''
}
},
mounted () {
this.name = this.$route.params.sheepName
}
4. 通过push的path属性进行query属性
父组件
<button @click="goSchool">query传参</button>
goSchool () {
this.$router.push({
path: '/school',
query: {
schoolName: '清华大学'
}
})
}
路由:
{
path: '/school',
name: 'school',
component: School
}
子组件
<h1>这里是{{schoolName}}</h1>
data () {
return {
schoolName: ''
}
},
mounted () {
this.schoolName = this.$route.query.schoolName
}