从入门到深入撸vue面试题

73 阅读1分钟

一.vue传参的方式及优缺点

1.vue 传参分为query传参和params传参

query传参:

 this.$router.push('/regist?kw='+this.keyword)     //字符串方式  
 this.$router.push(`/regist?kw=${this.keyword}`)  //模板字符串的方式
 //使用query对象方式传参
 this.$router.push({name:'regist',query:{kw:this.keyword}})
 
 使用路由传参的时候注意要在页面对应的路由加上name属性:
 如下:
 {
            path: '/search',
            component: Search,
            name: 'search',
            meta: {
                showFooter: true
            }
 }

params传参:与query传参一样,Params传参也有三种方式 1.字符串 2.模板字符串 3.对象方式

 this.$router.push('/search/'+this.keyword)    //字符串
 this.$router.push(`/search/${this.keyword}`)    //模板字符串
 注意:使用字符串与模板字符串传参的时候,需要在对应的路由种占位,如下:
 {
            path: '/search/:kw',  //kw占位
            component: Search,
            name: 'search',
            meta: {
                showFooter: true
            }
   }
             
 this.$router.push({name:"search",params:{kw:this.keyword}})  //对象方式
 使用对象的方式传参和query方式一样,也需要在路由中添加meta属性

2.如何指定params参数可传可不传?

关于这个问题,我们首先想到的肯定是如果有参数就写上,没参数就不写,这样不就实现了可传可不穿么!!!

但是这样写会有问题,接下来我们看代码:

如果有参数,我们正常写就写了,如下:

this.$router.push({name:"search",params:{kw:this.keyword}})

image.png

可以正常跳转,也可以正常传参

如果没有参数,我们肯定想到的就是不写不就行了么,看如下代码:(为了效果更明显,我们后面再添加一个query参数)

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

image.png

执行之后我们会发现,地址栏中不仅没有了Params参数,连search路径也都没有了,那么如何才能有路径而没有参数呢,我们只需要在参数占位后面添加一个问号就行了,看如下代码:

image.png

这样我们再执行的时候,路径就正常了:

image.png

3.params参数可以传递也可以不传递,但是如果传递是空串,如何解决?

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

如果params参数为空,我们传递的时候路径也是会出现问题的:如下图:

image.png

也是没有了路径,

解决方法:

this.$router.push({ name: "search", params: { kw: '' || undefined }, query: { kw: this.keyword } }) { path: '/search/:kw?', component: Search, name: 'search', meta: { showFooter: true } },

如果params的参数为空,只需要在后面添加 || undefined 即可,注意:路由占位后面的 问号 不能少

### 注:路由传递参数(对象写法)path是否可以结合params参数一起使用