Vue-多个可选路由器参数

时间:2019-08-11 21:33:01

标签: vue.js vuejs2 vue-router

我正在尝试构建具有多个(可选)搜索选项的组件。

路径可以是以下任意一个:

  • my-site.com/gallery
  • my-site.com/gallery/search+keyword
  • my-site.com/gallery/140
  • my-site.com/gallery/search+keyword/140/page/10

或任何其他组合

这就是我的路线

const galleryPageRoute = {
  path: '/gallery/:search?/:photocat?/:page(page\/\\d+)?',
  component: Gallery,
  name: 'Gallery',
  props: route => (Object.assign(route.params, { photocat: route.params.photocat, search: route.params.search, page: pageFromPath(route.path) }))
}

这就是我在组件中设置参数的方式

props: {
    page: {
      type: Number,
      required: true
    },
    photocat: {
      required: false
    },
    search: {
      type: String,
      required: false
    }
  },

filterCat(catid) {
      this.$router.push({name:'Gallery', params:{
        search: this.search ? this.search : undefined, 
        photocat: catid+'/'
      }});
    },

handleSubmit(result) {
      this.$router.push({name:'Gallery', params:{
        search: result.name,
        photocat: this.photocat ? this.photocat : undefined
      }});
    },

现在正在发生的事情是,如果缺少搜索参数,则上例中的140将被视为搜索参数,因此组件中的prop“搜索”将获得该值,但是,如您在filterCat()已为属性photocat设置了此ID

1 个答案:

答案 0 :(得分:0)

要与vue-router进行匹配,应使用以下语法(docs):

import VueRouter from 'vue-router'

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '/' },
    // asterisk can match anything
    { path: '/asterisk*' },
    // asterisk can match anything like params
    { path: '/asterisk/*' },
  ]
})