【问题标题】:Vue2 router with multiple, unordered, optional params具有多个无序可选参数的 Vue2 路由器
【发布时间】:2019-02-06 23:09:31
【问题描述】:

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

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

我可以用 '?' 做一些非常基本的事情。 (例如:/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 的经验,因此建议有任何想法。

谢谢

【问题讨论】:

    标签: vue.js vuejs2 vue-router


    【解决方案1】:

    您可以使用$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

    【讨论】:

    • 感谢@tony19 的回复和演示。我忘了提到 Vue 应用程序位于 Wordpress 之上,这限制了我可以用路由器做的事情。当前设置是我有一个仅在该搜索页面上运行的应用程序(以及产品页面的单独应用程序)
    猜你喜欢
    • 2016-02-15
    • 2014-05-04
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多