Dha*_*eda 3 javascript vue.js vuejs2
我从 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
}
}
}
Run Code Online (Sandbox Code Playgroud)
为了维护双向绑定,我当前使用计算属性,如下所示:
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";
}
}, ...
Run Code Online (Sandbox Code Playgroud)
这些计算属性通过以下方式连接到 HTML 代码上。
<input type="checkbox" checked v-model="attribute1">
<input type="checkbox" checked v-model="attribute2">
Run Code Online (Sandbox Code Playgroud)
这对于 VUE 中的双向绑定非常有效。但代码中存在严重重复。
我想到了另一种方法,使用 @change 事件来跟踪复选框中的更改:checked 属性并根据更改数据属性,但这似乎是一种绑定方式,并且在 Vue 控制台中,值仅在刷新时更新VUE 面板。
在这种特定场景下是否有更好的方法来实现双向绑定?
您可以通过简单地更新模板来实现此目的,例如:
<input type="checkbox" v-model="form.attribute1" :true-value="1" :false-value="0">
<input type="checkbox" v-model="form.attribute2" :true-value="1" :false-value="0">
Run Code Online (Sandbox Code Playgroud)
就是这样。您将不再需要任何计算属性。this.form.attribute1
当复选框被选中时,您将获得值为“1”;当未选中时,您将获得值为“0”。另外,如果您将form.attribute1
值设置为“1”,则默认情况下会选中该复选框,如下面的演示所示。
演示:
<input type="checkbox" v-model="form.attribute1" :true-value="1" :false-value="0">
<input type="checkbox" v-model="form.attribute2" :true-value="1" :false-value="0">
Run Code Online (Sandbox Code Playgroud)
new Vue({
el: '#app',
data(){
return {
form: {
attribute1: "1", //attribute 1 is true
attribute2: "0" //attribute 2 is false
}
}
}
})
Run Code Online (Sandbox Code Playgroud)