简体   繁体   中英

Vue.js - Pass data from child component to parent using emit but without button

I have a parent form template and each question of the form is inside a child component, like this

   <template>
      <question1
         @display-answer-1="setAnswer1"
      />
      <!-- other child components here... -->
   </template>
   
   <script>
   
   import Question1 from '...path...';
   
   export default{

      components: { Question1 },
      data() {
         answer1: ''
      },
      methods: {
         setAnswer1(answer1) {
             this.answer1 = answer1;
         }
      }
   };

and my child component is like this

<template>
   <input type="text" v-model="answer1"/>
   <div>
       <button
             type="button"
             @click="saveQ2"
       >Save
       </button>
   </div>
</template>

<script>

export default {
    data() {
        return {
            answer1: ''
        };
    },
    methods: {
        saveQ2() {
            const answer1 = this.answer1;
            this.$emit('display-answer-1', answer1);
        }
    }
};

This code works, but in this way I'm forced to put a button whenever there is a question to pass data from the child to the form template parent. Is there a smart alternative not to put a save button under each question?

you can use the blur event whenever an input gets unfocused it'll fire the event .

<template>
<input @blur="saveQ2" type="text" v-model="answer1"/>
</template>

<script>

export default {
data() {
    return {
        answer1: ''
    };
},
methods: {
    saveQ2() {
        const answer1 = this.answer1;
        this.$emit('display-answer-1', answer1);
    }
}

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM