使用 vue 路由器使查询参数具有反应性

abk*_*bks 2 javascript vue.js vue-router vuejs2

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

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

如果用户继续bar在输入字段中输入,我希望将 URL 更新为http://localhost:8080/search?query=foobar而无需通过路由器导航。

Dec*_*oon 5

如果你制作$route.query真实来源,那么当你想要改变它的值时,你只需要对$router.replace()更新的查询值进行操作。

袖口外:

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

...this.$route.query是保留可能存在的任何其他查询参数; 如果你只有q那么它是没有必要的(你也可能需要使用Object.assign()代替,因为现在对对象传播语法的支持是不完整的)。