vue中query和params传递参数
//我们在路由中配置了如下对象:
let options= {
routes:[
{
path:'/insertquery',
name:'query1',
component:()=>import('@/pages/insertquery')
},
{
path:'/insertparams1/:id/:name',
name:'params1',
component:()=>import('@/pages/insertparams1')
},
{
path:'/',
component:()=>import('@/pages/home')
}
]
}
先说query传参
query传参更像是原生中的get方式传参,参数会在url中以?id=xxx&name=xxx的形式存在。刷新不丢失。
传递时,分为以下几种形式。我们往 path:’/insertquery’中组件中传参:
<template>
<div style="display: flex;flex-direction:column">
<router-link :to=" '/insertquery?id='+dataId+'&name='+dataName">query传参</router-link>
<router-link :to="`/insertquery?id=${dataId}&name=${dataName}`">query传参</router-link>
<!--可以使用路由中的name和path中的任意一种-->
<router-link :to="{path:'/insertquery',query:{id:dataId,name:dataName} }">query传参</router-link>
<router-link :to="{name:'query1',query:{id:dataId,name:dataName} }">query传参</router-link>
<button @click="queryBtn1">query传参</button>
<button @click="queryBtn2">query传参</button>
</div>
</template>
<script>
export default {
name: "home",
data(){
return {
dataId:222,
dataName:'张三'
}
},
methods:{
queryBtn1(){
this.$router.push({
name:'query1',
query:{id:'22',name:this.dataName}
})
},
queryBtn2(){
this.$router.push({
path:'/insertquery',
query:{id:this.dataId,name:this.dataName}
})
}
}
}
</script>
<style scoped>
</style>
query接收参数 :this.$route.query.变量名
再说params传参 (对象写法下只能使用路由中的name)
<template>
<div style="display: flex;flex-direction:column">
<router-link :to=" '/insertparams1/'+dataId+'/'+dataName">params传参</router-link>
<router-link :to="`/insertparams1/${dataId}/${dataName}`">params传参</router-link>
<router-link :to="{name:'params1',params:{id:dataId,name:dataName} }">params往动态路由中传递,刷新参数不丢失</router-link>
<button @click="paramsBtn1">params往动态路由中传递,刷新参数不丢失</button>
<!--注意:对象的形式中只能路由中的name跳转,往普通路由跳转,刷新后参数会丢失(对象形式下,params参数不在url中)-->
<router-link replace :to="{name:'query1',params:{id:dataId,name:dataName} }">params往普通路由传递,刷新后会丢失</router-link>
<button @click="paramsBtn2">params往普通路由传递,刷新后会丢失</button>
</div>
</template>
<script>
export default {
name: "home",
data(){
return {
dataId:222,
dataName:'张三'
}
},
methods:{
paramsBtn1(){
//注意:params往动态路由中传递,刷新参数不丢失
this.$router.push({
name:'params1',
params:{id:'22',name:this.dataName}
})
},
paramsBtn2(){
//注意:这里传递后,刷新后会丢失(对象形式下,params参数不在url中)
this.$router.replace({
name:'query1',
params:{id:'22',name:this.dataName}
})
}
}
}
</script>
<style scoped>
</style>
params接收参数:this.$route.params