【发布时间】:2020-03-26 13:01:20
【问题描述】:
我有来自 MySQL 数据库的数据,格式为“1”和“0”,代表布尔值 true 和 false。这些值在 vue 组件中按以下方式设置:
data(){
return {
form : {
attribute_1 : "1", //attribute 1 is true
attribute_2 : "0", //attribute 2 is false
attribute_3 : "1", //attribute 3 is true
}
}
}
为了保持双向绑定,我目前使用的计算属性如下:
attribute1: {
get(){
return this.form.attribute_1 == "1" ? true : false ;
},
set(newValue){
this.form.attribute_1 = newValue ? "1" : "0";
}
},
attribute2: {
get(){
return this.form.attribute_2 == "1" ? true : false ;
},
set(newValue){
this.form.attribute_2 = newValue ? "1" : "0";
}
}, ...
这些计算属性以下列方式连接到 HTML 代码。
<input type="checkbox" checked v-model="attribute1">
<input type="checkbox" checked v-model="attribute2">
这对于 VUE 中的双向绑定非常有效。但是代码中有严重的重复。
我想到了另一种方法,使用@change 事件来跟踪复选框中的更改:checked 属性并根据它更改数据属性,但它似乎是一种绑定方式,并且在 Vue 控制台中的值仅在以下情况下更新我刷新了 VUE 面板。
在这种特殊情况下,有没有更好的方法来实现双向绑定?
【问题讨论】:
标签: javascript vue.js vuejs2