vueRouter参数

1.如何指定params参数可传可不传?
  • 路径报错:配置路由路径中已经使用/:id占位但不传递,

    this.$router.push({name:"search",query:{K:this.keyword}})
    

​ ***解决:***配置路由的时候在占位后面加问号

routes:[{
   path:"/search/:keyword?"
}]
2.params传递的是空串?
  • *** 路径中少search路径错***

    ​ ***解决:***传递加上undefined

    this.$router.push({name:"search",params:{keyword:""||undefined},query:{k:this.keyword}})
    
3.路由接收props数据?
  • 三种写法

    (1)布尔值

    //配置路由,可以把params(只有params)参数作为路由组件的属性
    routes:[{
      props:true
    }]
    //路由组件内接收
    export default{
    props:["keyword"]
    }//只会传递params的参数
    

    (2)对象写法

//配置路由,可以把params(只有params)参数作为路由组件的属性
routes:[{
  props:{a:1,b:2}
}]
//路由组件内接收
export default{
props:["a","b"]
}//只会传递params的参数

​ (3)函数写法

//传递
routes:[
{props:($route)=>{
return {keyword:$route.params.keyword,k:$routr.query.k}
}}]
//接收
props:['k']
4.编程式路由导航跳转多次会报错(NavigationDuplicated)

由于vue-router编程路由导航返回的是promise,需要对push重写,需要传入成功失败的回调

  • 通过给push传入成功失败的回调可以解决
this.$router.push({name:"search",params:{keyword:this.keyword},query:{k:this.keyword}},()=>(),()=>());//传入失败成功的回调,但是不治本所有编程导航都要使用,replce也要

在路由index中重写:replace相同

let Rpush=VueRouter.prototype.push;//先备份VueRouter的push方法
//重写Push方法,传递参数往哪里跳转location,成功失败的回调
VueRouter.prototype.push=function(location,resolve,reject){
if(resolve&&reject){
//使用apply参数是数组,call是逗号隔开
Rpush.call(this,location,resolve,reject)
//调用原来的需要改this直接调用this->window
}else{
Rpush.call(this,location,()=>{},()=>{})
}
}



//解决相同路径跳转报错问题
//使用push的方法
const RouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (to) {
  return RouterPush.call(this, to).catch(err => err)
}

//使用replace的方法
const RouterReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace (to) {
  return RouterReplace.call(this, to).catch(err => err)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值