【问题标题】:Make query parameter with vue router reactive使用 Vue 路由器响应式查询参数
【发布时间】:2018-09-10 04:35:42
【问题描述】:

我正在尝试使用 Vue 构建搜索页面,并且我希望用户在输入字段中输入的查询文本能够与 URL 中的查询参数产生反应 例如:

输入:foo 网址:http://localhost:8080/search?query=foo

如果用户继续在输入字段中键入bar,我希望在不通过路由器导航的情况下将 URL 更新为http://localhost:8080/search?query=foobar

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-router


    【解决方案1】:

    如果您将$route.query 设为source of truth,那么当您想要改变其值时,您只需使用更新后的查询值执行$router.replace() 操作。

    即兴表演:

    <input :value="$route.query.q" @input="onInput">
    
    onInput(e) {
      this.$router.replace({
        query: {
          ...this.$route.query,
          q: e.target.value,
        }
      })
    }
    

    ...this.$route.query 用于保留可能存在的任何其他查询参数;如果您只有q,则没有必要(您也可能需要使用Object.assign(),因为目前对object spread syntax 的支持尚不完善)。

    【讨论】:

      猜你喜欢
      • 2017-06-22
      • 1970-01-01
      • 1970-01-01
      • 2019-10-15
      • 2017-12-01
      • 2017-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多