vue-router传参

158 阅读1分钟
一、字符串传参方式(params传参和query传参)
// 字符串拼接写法(在面对多个数据时,写法复杂)
this.$router.push('/search/' + this.keyword + '?k=' + this.keyword.toUpperCase());
二、模板字符串传参方式
this.$router.push(`/search/${this.keyword}?k=${this.keyword.toUpperCase()}`);
三、通过params参数进行传参(对象传参方式)
  1. 通过parmas参数进行传参时,需要在路径中进行占位,需要通过name属性进行使用,path是不能配合params参数一起使用的。
//路由配置文件
{
    name:'search'
    path:'/search/:keyword'   //在使用params参数进行传参时需要在path中进行占位
    component:Search,
    meta:{
             showFooter:true
          }
}
  1. params参数与query参数可以一起传递,具体用法参考如下:
this.$router.push({
    name:'search',
    params:{keyword:this.keyword},
    query:{k:this.keyword.toUppreCase()}
})
//路由配置文件
{
    name:'search'
    path:'/search/:keyword?'   //使用?分隔params参数以及query参数,query参数会自动拼接到?后面
    component:Search,
    meta:{
             showFooter:true
          }
}
四、如何指定params参数可以传递也可以不传递
    path:"/search/:keyword?"
  • 在配置路由的时候,在占位的后面添加一个问号表示params参数可传可不传
  • 如果params传递的是空串,可以通过undefined解决
this.$router.push({
    name:'search',
    params:{keyword:'' || undefined}, //如果传递的是空字符串,返回undefined
    query:{k:this.keyword.toUppreCase()}
})
五、路由组件通过props传递数据
  • 在路由设置中设置props属性为true
{
     path:"/search/:keyword",   //  使用:keyword进行占位
     component:Search,
     meta:{
             showFooter:true
          },
     props:true    //通过props传递数据
}