[Vuejs]-On key press update parent data from child Vue.js

0👍

You can change the parent from child component the same way you do emiting other events like onchange, onkeyup, onkeydown etc.

Vue.component('parent', {
    data() {
    return {
      parentValue: ''
    };
  },

  template: `
    <div>
      <label>Parent state value:</label>
      {{parentValue}}
      <br/><br/>
      <label>input is the child component:</label>
      <br/>
      <child @fromChild="fromChild"></child>
    </div>
  `,

  methods: {
    fromChild(value) {
        this.parentValue = value
      console.log(value) // someValue
    }
  }
})

Vue.component('child', {  
    template: `
    <input 
        v-on:keyup="updateParent($event.target.value)" 
      placeholder="type something"
    />
  `,

  methods: {
    updateParent(value) {
        console.log(value)
      this.$emit("fromChild", value);
    }
    },
})

new Vue({
  el: "#app",
  data: {
    label: 'in Vue'
  },
  methods: {
    toggle: function(todo) {
        todo.done = !todo.done
    }
  }
})

I’ve prepared a working example here.

Leave a comment