programing

Vue JS의 확인란에 대한 적절한 양방향 바인딩

itsource 2022. 7. 28. 23:00
반응형

Vue JS의 확인란에 대한 적절한 양방향 바인딩

MySQL 데이터베이스에서 부울 참과 거짓을 나타내는 "1"과 "0"의 데이터가 있습니다.이러한 값은 다음과 같은 방법으로 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 이벤트를 사용하여 체크박스의 변경을 추적하고 그에 따라 데이터 속성을 변경할 수 있는 다른 방법이 있습니다.그러나 Vue 콘솔의 값은 VUE 패널을 새로 고칠 때만 갱신됩니다.

이 특정 시나리오에서 쌍방향 바인딩을 실현하는 더 좋은 방법이 있습니까?

제가 가장 좋아하는 솔루션은 다음과 같은 목표를 달성하기 위한 컴포넌트를 작성하는 것입니다.
[내 체크박스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>

다음과 같이 템플릿을 업데이트하기만 하면 됩니다.

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

그리고 이것이 마지막입니다.계산된 속성은 더 이상 필요하지 않습니다.얻을 수 있을 것이다this.form.attribute1체크 박스를 온으로 했을 경우는 「1」, 오프했을 경우는 「0」으로 합니다.또, 설정했을 경우는form.attribute1값을 "1"로 지정하면 아래 데모에서와 같이 기본적으로 확인란이 선택됩니다.

데모:

new Vue({
  el: '#app',
  data(){
    return {
      form: {
        attribute1: "1", //attribute 1 is true
        attribute2: "0"  //attribute 2 is false
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <input type="checkbox" v-model="form.attribute1" :true-value="1" :false-value="0">
  <label for="checkbox">{{ form.attribute1 }}</label><br/><br/>
  <input type="checkbox" v-model="form.attribute2" :true-value="1" :false-value="0">
  <label for="checkbox">{{ form.attribute2 }}</label><br/><br/>
</div>

언급URL : https://stackoverflow.com/questions/60867885/appropriate-two-way-binding-for-checkboxes-in-vue-js

반응형