IT이야기

Vue의 하위 구성 요소에서 입력 값 가져오기

cyworld 2022. 5. 24. 21:57
반응형

Vue의 하위 구성 요소에서 입력 값 가져오기

자식 구성 요소에서 모든 입력 값을 검색하려고 함(client그리고advice, 아래 참조), 그러나 어떻게 진행해야 할지 확실하지 않다.

client.vue

<template>
    <div id="client">
        <input type="text" v-model="client.name" />
        <input type="text" v-model="client.code" />
    </div>
</template>

<script>
    export default {
        data() {
            return {
                client: {
                    name: '',
                    code: '',
                }
            }
        }
    }
</script>

충고.vue

<template>
    <div id="advice">
        <input type="text" v-model="advice.foo" />
        <input type="text" v-model="advice.bar" />
        <div v-for="index in 2" :key="index">
            <input type="text" v-model="advice.amount[index]" />
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                advice: {
                    foo: '',
                    bar: '',
                    amount:[]
                }
            }
        }
    }
</script>

각 구성요소는 위의 예보다 더 많은 필드를 가진다.

내 홈 페이지(부모)는 다음과 같이 단순해 보인다.

<template>
    <form id="app" @submit="printForm">
        <clientInfo />
        <advice />
        <input type="submit" value="Print" class="btn" />
    </form>
</template>

<script>
    import clientInfo from "@/components/clientInfo.vue";
    import advice from "@/components/advice.vue";

    export default {
        components: {
            clientInfo,
            advice
        },
        methods: {
            printForm() {}
        }
    }
</script>

내 첫 번째 생각은$emit, 그러나 어떻게 20개 이상의 분야로 효율적으로 그것을 할 수 있을지는 확실하지 않다.@emitMethod="parentEmitMethod"각 방면에 걸쳐

나의 두 번째 생각은 (아래에서 본 바와 같이) Vuex 상점을 갖는 것이었지만, 모든 주를 한 번에 어떻게 구해야 할지 모르겠고 내가 해야 할지 잘 모르겠다.

new Vuex.Store({
    state: {
        client: {
            name:'',
            code:''
        },
        advice: {
            foo:'',
            bar:'',
            amount:[]
        }
    }
})

당신은 그 가치들을 얻을 수 있을 것이다.form<input>s 또는<textarea>속성이 있는 s(일반적인 속성은 무시됨).양식에 다음이 포함된 중첩된 Vue 구성 요소가 있는 경우에도 작동 가능<input>s

export default {
  methods: {
    printForm(e) {
      const form = e.target
      const formData = new FormData(form) // get all named inputs in form
      for (const [inputName, value] of formData) {
        console.log({ inputName, value })
      }
    }
  }
}

데모를 하다

나는 당신이 원하는 것을 성취할 수 있다고 생각한다. 당신이 무언가를 쓸때 당신은 당신이 원하는 것을 성취할 수 있다고 생각한다.@change이렇게 하면 입력 값이 변경될 때 메소드가 트리거되며, 대신 버튼이나 원하는 것을 사용할 수 있다.

하위 구성 요소

<input type="text" v-model="advice.amount[index]" @change="emitCurrStateToParent ()"/>

덧붙여야 한다.@change="emitCurrStateToParent ()"네가 가진 모든 입력에 있어

emitCurrStateToParent () {
    this.$emit("emitCurrStateToParent", this.advice)
}

그러면 상위 구성 요소

<child-component v-on:emitCurrStateToParent="reciveDataFromChild ($event)"></child-component>
reciveDataFromChild (recivedData) {
    // Do something with the data
}

나는 대신에 버튼을 사용할 것이다.@change, "Save" 버튼 idk처럼, vuex도 마찬가지, 당신은 그것을 사용할 수 있다.@change사건

saveDataAdviceInStore () {
    this.$store.commit("saveAdvice", this.advice)
}

그럼 가게에서

mutations: {
    saveAdvice (state, advice) {
        state.advice = advice
    }
}    

v-model을 사용자 지정 구성 요소와 함께 사용할 수 있음다음과 같이 사용하고 싶다고 가정해 봅시다.

<advice v-model="adviceData"/>

이를 위해, 당신은 당신의 조언 요소 안에서 당신의 입력 요소들에 대한 가치 변동을 주시한 다음 그 값을 가진 입력 이벤트를 내보내야 할 것이다.이렇게 하면 조언데이터 바인딩된 속성이 업데이트된다.이를 위한 한 가지 일반적인 방법은 다음과 같은 조언 구성요소에 감시자를 포함하는 것일 수 있다.

export default {
  data() {
    return {
      advice: {
        foo: '',
        bar: '',
        amount:[]
      }
    }
  },
  watch: {
    advice: {
      handler: function(newValue, oldValue) {
        this.$emit('input', newValue);
      },
      deep: true,
    }
  },
}

이렇게 하면 각 입력 필드에 핸들러를 추가할 필요가 없다.조언 객체에서 중첩된 데이터에 대한 변경을 탐지해야 할 경우 심층 옵션이 포함되어야 한다.

참조URL: https://stackoverflow.com/questions/57012751/get-input-values-from-child-components-in-vue

반응형