gpt4 book ai didi

javascript - Vue JS中复选框的适当两种方式绑定(bind)

转载 作者:行者123 更新时间:2023-12-04 16:27:20 25 4
gpt4 key购买 nike

我有来自 MySQL 数据库的数据,形式为“1”和“0”,分别代表 bool 值 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
}
}
}

为了保持双向绑定(bind),我目前使用如下计算属性:

 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 中的双向绑定(bind)非常有效。但是代码中有严重的重复。

我想到的另一种方法是使用@change 事件来跟踪复选框中的更改:checked 属性并根据更改数据属性但这似乎是一种绑定(bind)方式,并且在 Vue 控制台中值仅在以下情况下更新我刷新 VUE 面板。

在这种特定情况下,是否有更好的方法来实现双向绑定(bind)?

最佳答案

我最喜欢的解决方案是创建组件来实现:
我的 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>

并在其他组件中使用它:

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

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

关于javascript - Vue JS中复选框的适当两种方式绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60867885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com