Vue中路由传参

81 阅读1分钟

Vue路由传参


一、参数有几种写法?

  • params参数:属于路径中的一部分,注意:在配置路由的时候,需要占位
  • query参数:不属于路径中的一部分,
    类似ajax中的queryString /home?k=v&k=v,不需要占位

二、路由传参的三种形式

  • 字符串
this.$router.push("/search/" + this.keyword + "?k=" +   this.keyword.toUpperCase())
  • 模板字符串
this.$router.push(`/search/${this.keyword}?k=${this.keyword.toUpperCase()}`)
  • 对象
this.$router.push({
        name: "search",
        params: { keyword: this.keyword },
        query: { k: this.keyword.toUpperCase() },
      });

Search/index.vue

<template>
    <div>
        我是搜索
        <h1>params ------ {{$route.params.keyword}}</h1>
        <h1>query ------{{$route.query.k}}</h1>
    </div>
</template>

Header/index.vue

data() {
    return {
      keyword: "",
    };
  },
methods: {
    goSearch() {
      // 路由传参三种形式
      // 第一种形式 字符串形式
      // this.$router.push("/search/" + this.keyword + "?k=" +   this.keyword.toUpperCase())
      // 第二种形式 模板字符串形式
      // this.$router.push(`/search/${this.keyword}?k=${this.keyword.toUpperCase()}`)
      // 第三种形式 对象形式(常用)
      this.$router.push({
        name: "search",
        params: { keyword: this.keyword },
        query: { k: this.keyword.toUpperCase() },
      });
    },
  },

router/index.js

export default new VueRouter ({
routes:[
    {
      path:'/search/:keyword',
      component:Search,
      meta:{show:true},
      name:'search'
     },
    ]
})

1662988210617.png


三、路由传参相关面试题

  1. 路由传递参数(对象写法)path是否可以结合params参数一起使用?
    答:路由跳转传参的时候,对象写法可以是path、params形式,
    但是,path这种写法是不能和params参数一起使用
 goSearch(){
     this.$router.push({
        path:'/search',
        params:{keyword:this.keyword},
        query:{k:this.keyword.toUpperCase()},
      })
    },

1662988703151.png

  1. 如何指定params参数可传可不传?
    答:如果要求传递params参数,你却不传,会发现url有问题,因此,
    在配置路由的时候,在占位的后面加个问号,代表可以传递或者不传递 path:'/search/:keyword?'
this.$router.push({
        name:'search',
        query:{k:this.keyword.toUpperCase()},
      })

1662989333449.png

  1. params参数可以传递也可以不传递,但如果传递空串,如何解决?
    答:使用undefined解决:params参数可以传递、可以不传递(空串)
    params:{keyword:''||undefined},
this.$router.push({
        name:'search',
        params:{keyword:''},
        query:{k:this.keyword.toUpperCase()},
      })

1662989909607.png

  1. 路由组件能不能传递props数据?(不常用,了解)
    答:可以,三种写法:布尔值、对象、函数

Search/index.vue

<template>
    <div>
        我是搜索
        <h1>params ------ {{$route.params.keyword}}---{{keyword}}</h1>
        <h1>query ------{{$route.query.k}}----{{k}}</h1>
    </div>
</template>
<script>
export default {
    name: '',
    props:['keyword''k']
}
</script>

router/index.js

routes:[
    {
      path:'/search/:keyword',
      component:Search,
      meta:{show:true},
      name:'search'//props:true, //布尔值写法:params
      //props:{keyword:1,k:2}  //对象写法:额外的给路由组件传递一些props
      //函数写法
      props:($route) =>{
      return {keyword:$route.params.keyword,k:$route.query.k};
      }
     },
    ]

1662991771987.png

参考:

www.bilibili.com/video/BV1Vf… (part:8、9)