Search code examples
javascriptvue.jsvuex

how do I clear the v-model in the child component from the parent?


Please help me. I am trying 10hours in a row and doesn't work. I want when i clicked in @click="cleanDataForm" in Parent Component => v-model text in Child component will "" . And i tryed do it with props , computed and nothing. I will be very kind if you help

//Parent

<template>
    <div class="Main">
        <div class="comment">
            <Smiles
            />
            <div class="btns">
                <button id="btn--send" type="submit" @click="sendData">Send data</button>
                <button id="btn--clear" @click="cleanDataForm">clean data</button>
            </div>
        </div>
    </div>
</template>

// Child

<template>
    <div class="container">
        <textarea
            v-model="text"                          !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1
            ref="smilesTextarea"
            placeholder="Введите комментарий"
        ></textarea>
        <button @click="showSimiles">😀</button>
    </div>
</template>

And i need this.text will "" when i clicked send data in Parent. I tryed with vuex but nothing. Please help


Solution

  • One way of doing that with props and emit:

    Vue.component('child', {
      template: `
        <textarea
          v-model="text" 
          ref="smilesTextarea"
          placeholder="Введите комментарий"
        ></textarea>
      `,
      props: ['clear'],
      data() {
        return {
          text: ''
        }
      },
      watch: {
        clear(newVal) {
          this.text = ''
          this.$emit('cleared')
        }
      }
    })
    new Vue({
      el: '#demo',
      data() {
        return {
          clear: false
        }
      },
      methods: {
        cleanDataForm() {
          this.clear = true
        },
        resetClear() {
          this.clear = false
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="demo">
      <button id="btn--clear" @click="cleanDataForm">clean data</button>
      <child :clear="clear" @cleared="resetClear"></child>
    </div>