具有多个无序可选参数的 Vue2 路由器

Vue2 router with multiple, unordered, optional params

我不确定这是否可行,但这是我正在尝试做的事情:

我正在制作一个页面来显示不同产品的搜索结果。产品有许多多重过滤器(例如尺寸、重量、颜色、国家等)。 我想要 url 到 'describe' 那些过滤器。

我可以用'?'做一些非常基本的事情(例如:/color/:color?/country/:country)。但它强制执行特定顺序,并且需要输入 url 中的所有部分。我正在处理 10 多个过滤器,其中一些可以有多种颜色。

我正在考虑的非 Vue 选项类似于:example.com/search/?weight=10-20&color=blue&color=red&country=usa.

这需要使用 Window.history.push,并使用 javascript 解析 queryString,而我可能根本无法使用 VueRouter。

我对 Vue.js 没有经验,所以建议任何想法。

谢谢

您可以使用 $route.query 从当前 URL 访问查询参数。不用自己解析了。

您的模板可以直接访问查询参数:

<div v-if="$route.query.weight">weight: {{ $route.query.weight }}</div>
<div v-if="$route.query.country">country: {{ $route.query.country }}</div>
<div v-if="$route.query.color">color: {{ $route.query.color }}</div>

您的脚本可以像这样访问参数:

methods: {
  logQueryParams() {
    console.log("weight", this.$route.query.weight)
    console.log("country", this.$route.query.country)
    console.log("color", this.$route.query.color)
  }
}

您的脚本还可以 watch 更改参数:

watch: {
  ["$route.query.weight"](weight, oldWeight) {
    console.log("new weight", weight);
  }
}

并且您可以使用 $router.push:

强制推送一条新路线
methods: {
  searchCanada() {
    this.$router.push({ name: "search", query: { country: "canada" } });
  }
}

demo