Vue2路由器多,无序的,可选PARAMS

问题描述 投票:1回答:1

我不知道这甚至有可能,但这里是我想要做的事:

我工作在页面上展示不同产品的搜索结果。该产品有许多多个过滤器(例如尺寸,重量,颜色,国家等)。我想链接到“形容”这些过滤器。

我能够做一些事情非常基本的“?” (例如:/颜色/?彩/国家/:国家)。但它迫使一个特定的顺序,并在URL的所有部分需要输入。我处理过10的过滤器,其中一些可以有多种颜色。

我正在考虑一个非Vue的办法是这样的:example.com/search/?weight=10-20&color=blue&color=red&country=usa。

这需要使用Window.history.push,并解析与JavaScript查询字符串,而我可能会不能够在所有使用VueRouter。

我不会跟Vue.js经历了那么任何想法,建议。

谢谢

vue.js vuejs2 vue-router
1个回答
1
投票

你可以使用$route.query从当前URL访问的查询参数。无需自己解析它。

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

<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>

和你的脚本可以访问这样的PARAMS:

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

您的脚本也可以watch更改到PARAMS:

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

你可以推势在必行用$router.push一个新的路径:

methods: {
  searchCanada() {
    this.$router.push({ name: "search", query: { country: "canada" } });
  }
}

demo

© www.soinside.com 2019 - 2024. All rights reserved.