Javascript Vue JS中复选框的适当双向绑定

Javascript Vue JS中复选框的适当双向绑定,javascript,vue.js,vuejs2,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

我有来自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面板时更新


在这个特定场景中,是否有更好的方法实现双向绑定

只需更新模板即可实现这一点,如:

<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">

{{form.attribute1}}

{{form.attribute2}}


我最喜欢的解决方案是创建组件来实现这一点:
My Checkbox.vue组件:

<template>
    <input type="checkbox" :checked="isChecked" @change="change" />
</template>

<script>
export default {
    props: {
        value: {}
    },
    computed: {
        isChecked() {
            return this.value === "1" || this.value === true;
        }
    },
    methods: {
        change(e) {
            this.$emit("input", e.target.checked ? "1" : "0");
        }
    }
};
</script>

导出默认值{
道具:{
值:{}
},
计算:{
isChecked(){
返回this.value==“1”| this.value===true;
}
},
方法:{
更改(e){
该.$emit(“输入”,例如,选中目标?“1”:“0”);
}
}
};
并在其他组件中使用:

<template>
    <div>
        <Checkbox v-model="isChecked" />
    </div>
</template>

<script>
import Checkbox from "./Checkbox";
export default {
    components: {
        Checkbox
    },
    data: () => ({
        isChecked: "1"
    })
};
</script>

从“/Checkbox”导入复选框;
导出默认值{
组成部分:{
复选框
},
数据:()=>({
被选中:“1”
})
};

这很有效。非常感谢你。我唯一需要更改的是在:true value和:false value属性中的值周围加上引号。