vue中路由传参
- 使用router-link进行路由导航,传递参数
父组件中使用标签进行导航
//child是子页面路由路径,123是需要传递的参数
<router-link to="/child/123">click</router-link>
子组件中使用this.$route.params.num来接收路由参数
<template>
<div class="child">
{{num}}
</div>
</template>
<script>
export default{
name:'child',
data(){
return{
num:0,
}
},
mounted(){
this.num = this.$route.params.num
}
}
</script>
路由配置文件router/index.js
{
path:'/child/:num', // num用来为参数占位
name:'child',
component:child
}
地址:localhost:8080/#/child/123
- 直接调用$router.push 实现携带参数的跳转
父组件
<template>
<ul>
<li v-for="itemId in 3" :key="itemId" @click="toChild(itemId)">{{itemId}}</li>
</ul>
</template>
// 模板渲染中调用函数,传递参数
<script>
export default{
name:'home',
data(){
return{
num:0,
}
},
methods:{
toChild(id){
this.$router.push({
path:`/child/${id}`
})
}
}
}
</script>
子组件中:
<template>
<div class="child">
{{this.$route.params.id}}
</div>
</template>
路由配置文件中:
{
path:'/child/:id', //id用来为参数占位
name:'child',
component:Child
}
地址:localhost:8080/#/child/1
- 通过路由属性中的name来确定匹配的路由,通过params来传递参数
父组件:
<template>
<button @click="toClick">click</button>
</template>
<script>
export default{
name:'home',
data(){
return{
num:0,
}
},
methods:{
toChild(){
this.$router.push({ //使用name来匹配路由
name:'childView',
params:{
id:1
}
})
}
}
}
</script>
子组件中:
<template>
<div class="child">
{{this.$route.params.id}}
</div>
</template>
路由配置问件中:
{
path:'/child',
name:'childView',
cmponent:Child,
}
地址:localhost:8080/#/child
- 使用path来匹配路由,然后通过query来传递参数,这种情况下 query传递的参数会显示在url后面?id=?
父组件中:
<template>
<button @click="toClick">click</button>
</template>
<script>
export default{
name:'home',
data(){
return{
num:0,
}
},
methods:{
toChild(){
this.$router.push({ //使用name来匹配路由
path:"/child",
query:{
id:1
}
})
}
}
}
</script>
子组件中:
<template>
<div class="child">
{{this.$route.params.id}}
</div>
</template>
路由配置文件中:
{
path:'/child',
name:'child',
component:Child,
}
地址:localhost:8080/#/child?id=1
总结:
- this.$router.push进行编程式路由跳转
- router-link 进行页面按钮式路由跳转
- this.$route.params获取路由传递参数
- this.$route.query获取路由传递参数
- params 和 query 都是传递参数的,params不会在url上面出现,并且params参数是路由的一部分,是一定要存在的 query则是我们通常看到的url后面的跟在?后面的显示参数