【发布时间】:2019-11-12 20:27:02
【问题描述】:
在使用 class-style components 时,是否可以在 vuejs 中使用 双向计算 属性?在我的情况下,给定一个带有简单 vuex 商店的应用程序,有没有办法使用v-model 将商店值绑定到 select?
在vuex documentation中有一个双向绑定的例子:
// ...
computed: {
message: {
get () {
return this.$store.state.obj.message
},
set (value) {
this.$store.commit('updateMessage', value)
}
}
}
但是我没有让它与类组件一起使用。我尝试了类似的东西
private get myvalue(): boolean {
return store.state.myvalue;
}
/* Same type of function I would use when using @input one-way binding*/
private set myvalue(e: Event /* Wrong type for the setter... */) {
const target: HTMLSelectElement = e.target as HTMLSelectElement;
const value = target.value;
if (Boolean(value)) {
store.commit("myvalue", target.value);
}
}
但这显然行不通,因为 getter/setter 总是具有相同的数据类型。 myvalue 的类型是 bool,但是将它传递给这两个函数并不能正常工作,因为当绑定到 select 时像这样
<select v-model="myvalue">
<option value="false">No</option>
<option value="true">Yes</option>
</select>
setter 似乎没有得到值。
我还尝试手动将值绑定到select(就像您对文本输入所做的那样),但在select 选项上使用:selected 不起作用(始终选择第一个选项)。
【问题讨论】:
-
如果
myvalue是布尔值,那么您可能需要通过执行:value="false"和:value="true"来确保选项值也是布尔值而不是字符串。 -
@DecadeMoon 我会调查的。我在测试是否选择了选项时检查了这一点,但在设置值时没有检查。感谢您的提示。
标签: javascript html vue.js data-binding