今天介绍路由传递参数的方式。首先要明白路由跳转的两种方式一种是声明式导航另一种是编程式导航。
参数的形式:
我们在网页中点击链接实现网页的切换;在Vue项目中点击
router-link :通过里面的to属性实现路由跳转
由上面连两张图片可以卡看出router-link 在传递参数时如果使用params形式传参,只能配合组件路由的name使用,而不能使用path。这里的name是在router.js中声明路由时定义的name名
然后我们继续测试:
发在在使用qurey参数时我们使用path或者name方式都可以进行传参,但是有一点和params参数不同的是query参数会显示在网址上面。
继续探究我们想要在query上面传递一个对象形式的参数,那么他会怎么显示呢?
你可以看见它的网址上面的参数是一个看不懂的字符串,其实这个就是经过加密的,我们在终端输出还是可以拿到的.
在使用router-link时使用params参数不会在网址栏显示,query会显示,在使用路由的name进行传参时只能够配合params使用,path则params、query都可以,也可以传递对象参数但是会被加密。
利用组件实例的$router.push()或$router.replace()方法实现路由的跳转。一般使用push方式的多。下面介绍路由传递参数的几种写法:
传递参数 – this.$router.push({path: ’ 路由 ', query: {key: value}})
参数取值 – this.$route.query.key
使用这种方式,传递参数会拼接在路由后面,出现在地址栏.。
this.$router.push('/search/'+this.keyword+"?k="+this.keyword)
模板字符串形式 (query)
this.$router.push(`/search/${this.keyword}?k=${this.keyword}`)
this.$router.push({name:'search',params:{keyword:this.keyword||undefined}})
配合undefined使用,因为如果是空串路径会出现问题
this.$router.push({name:'search',params:{keyword:this.keyword||undefined}})
path结合params参数写法:
let location={
name:'search',
params:{keyword:this.keyword||undefined}
}
if(this.$route.query){
location.query=this.$route.query
}
this.$router.push(location)
?可以在路由占位符后指定可穿可不传: path:'/detail/:skuid?'
必须现在路由下定义props:true
bool:只有params参数
对象写法:{a:1,b:2}
函数写法(不常用)
props:($route)=>{
return{
keyword:$route.params.keyword,//举例子
k:$route.query.k,//举例子
}
}