使用 vue router reactive 使查询参数
Make query parameter with vue router reactive
我正在尝试使用 Vue 构建一个搜索页面,我希望用户在输入字段中输入的查询文本与 URL 中的查询参数反应
例如:
输入:foo
url: http://localhost:8080/search?query=foo
如果用户继续在输入字段中键入 bar
,我希望将 URL 更新为 http://localhost:8080/search?query=foobar 而无需通过路由器导航。
如果您将 $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()
instead since support for object spread syntax 现在是不完整的)。
我正在尝试使用 Vue 构建一个搜索页面,我希望用户在输入字段中输入的查询文本与 URL 中的查询参数反应 例如:
输入:foo url: http://localhost:8080/search?query=foo
如果用户继续在输入字段中键入 bar
,我希望将 URL 更新为 http://localhost:8080/search?query=foobar 而无需通过路由器导航。
如果您将 $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()
instead since support for object spread syntax 现在是不完整的)。