nag*_*hun 6 javascript data-binding vue.js vue-router
我想将输入字段绑定到vue.js中的路由参数.
<input v-model="$route.params.query"/>
Run Code Online (Sandbox Code Playgroud)
可能吗?
Kir*_*man 12
我找到的最直接的方法如下:
<input v-model="foo" />
Run Code Online (Sandbox Code Playgroud)
-
data() {
return {
foo: this.$route.query.foo
};
},
watch: {
foo(newVal) {
this.$router.push({ query: { ...this.$route.query, foo: newVal } });
},
'$route.query.foo': function(val) {
this.foo = val;
}
}
Run Code Online (Sandbox Code Playgroud)
一段时间过去了,但由于文档说“使用计算属性而不是命令式手表回调通常是更好的主意”,我想我会添加这个我成功测试的模式,并且看起来更优雅恕我直言。
这个想法是使用computed
显式get
和set
方法链接到查询参数的属性,并将输入绑定v-model
到该属性。
所以在你的模板中:
<input v-model="query_param"/>
Run Code Online (Sandbox Code Playgroud)
然后在您的计算属性中:
computed: {
query_param: {
get() {
return this.$route.query.your_query_param
},
set(value) {
/* Here I use replace so that you're not actually
pushing a new page to the history stack */
this.$router.replace({
query: {
...this.$route.query,
your_query_param: value
}
})
}
}
}
Run Code Online (Sandbox Code Playgroud)
这当然适用于单个查询参数。如果您有多个输入要绑定到不同的参数,只需以相同的方式放置其他计算属性即可。
对的,这是可能的。在我的代码中,我有一个<select>
要更改的元素,我想将所选值作为查询附加到 url 中。所以,我这样做了:
我以前的网址是:
本地主机:8080/书籍
<select class="form-control" v-on:change="appendQueryToUrl" v-model="filterData.genre">
methods: {
appendQueryToUrl() {
this.$router.push({query: {genre: this.filterData.genre}})
}
}
Run Code Online (Sandbox Code Playgroud)
其中风格是我的键, this.filterData.genre 是我的本地对象值。现在我的网址如下所示:
localhost:8080/books/?genre=Computer
谢谢,如有错误请通知我。
归档时间: |
|
查看次数: |
2889 次 |
最近记录: |