[javascript] vuejs update parent data from child component

I'm starting to play with vuejs (2.0). I built a simple page with one component in it. The page has one Vue instance with data. On that page I registered and added the component to html. The component has one input[type=text]. I want that value to reflect on the parent (main Vue instance).

How do I correctly update the component's parent data? Passing a bound prop from the parent is not good and throws some warnings to the console. They have something in their doc but it is not working.

This question is related to javascript vue.js vue-component

The answer is


In child component:

this.$emit('eventname', this.variable)

In parent component:

<component @eventname="updateparent"></component>

methods: {
    updateparent(variable) {
        this.parentvariable = variable
    }
}

I think this will do the trick:

@change="$emit(variable)"


The correct way is to $emit() an event in the child component that the main Vue instance listens for.

// Child.js
Vue.component('child', {
  methods: {
    notifyParent: function() {
      this.$emit('my-event', 42);
    }
  }
});

// Parent.js
Vue.component('parent', {
  template: '<child v-on:my-event="onEvent($event)"></child>',
  methods: {
    onEvent: function(ev) {
      v; // 42
    }
  }
});

his example will tell you how to pass input value to parent on submit button.

First define eventBus as new Vue.

//main.js
import Vue from 'vue';
export const eventBus = new Vue();

Pass your input value via Emit.
//Sender Page
import { eventBus } from "../main";
methods: {
//passing data via eventbus
    resetSegmentbtn: function(InputValue) {
        eventBus.$emit("resetAllSegment", InputValue);
    }
}

//Receiver Page
import { eventBus } from "../main";

created() {
     eventBus.$on("resetAllSegment", data => {
         console.log(data);//fetching data
    });
}

It is also possible to pass props as Object or Array. In this case data will be two-way binded:

(This is noted at the end of topic: https://vuejs.org/v2/guide/components.html#One-Way-Data-Flow )

_x000D_
_x000D_
Vue.component('child', {_x000D_
  template: '#child',_x000D_
  props: {post: Object},_x000D_
  methods: {_x000D_
    updateValue: function () {_x000D_
      this.$emit('changed');_x000D_
    }_x000D_
  }_x000D_
});_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    post: {msg: 'hello'},_x000D_
    changed: false_x000D_
  },_x000D_
  methods: {_x000D_
    saveChanges() {_x000D_
        this.changed = true;_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  <p>Parent value: {{post.msg}}</p>_x000D_
  <p v-if="changed == true">Parent msg: Data been changed - received signal from child!</p>_x000D_
  <child :post="post" v-on:changed="saveChanges"></child>_x000D_
</div>_x000D_
_x000D_
<template id="child">_x000D_
   <input type="text" v-model="post.msg" v-on:input="updateValue()">_x000D_
</template>
_x000D_
_x000D_
_x000D_


In the child

 <input
            type="number"
            class="form-control"
            id="phoneNumber"
            placeholder
            v-model="contact_number"
            v-on:input="(event) => this.$emit('phoneNumber', event.target.value)"
    />

data(){
    return {
      contact_number : this.contact_number_props
    }
  },
  props : ['contact_number_props']

In parent

<contact-component v-on:phoneNumber="eventPhoneNumber" :contact_number_props="contact_number"></contact-component>


 methods : {
     eventPhoneNumber (value) {
      this.contact_number = value
    }

In Parent Conponent -->

data : function(){
            return {
                siteEntered : false, 
            };
        },

In Child Component -->

this.$parent.$data.siteEntered = true;


I agree with the event emitting and v-model answers for those above. However, I thought I would post what I found about components with multiple form elements that want to emit back to their parent since this seems one of the first articles returned by google.

I know the question specifies a single input, but this seemed the closest match and might save people some time with similar vue components. Also, no one has mentioned the .sync modifier yet.

As far as I know, the v-model solution is only suited to one input returning to their parent. I took a bit of time looking for it but Vue (2.3.0) documentation does show how to sync multiple props sent into the component back to the parent (via emit of course).

It is appropriately called the .sync modifier.

Here is what the documentation says:

In some cases, we may need “two-way binding” for a prop. Unfortunately, true two-way binding can create maintenance issues, because child components can mutate the parent without the source of that mutation being obvious in both the parent and the child.

That’s why instead, we recommend emitting events in the pattern of update:myPropName. For example, in a hypothetical component with a title prop, we could communicate the intent of assigning a new value with:

this.$emit('update:title', newTitle)

Then the parent can listen to that event and update a local data property, if it wants to. For example:

<text-document   
 v-bind:title="doc.title"  
 v-on:update:title="doc.title = $event"
></text-document>

For convenience, we offer a shorthand for this pattern with the .sync modifier:

<text-document v-bind:title.sync="doc.title"></text-document>

You can also sync multiple at a time by sending through an object. Check out the documentation here


Child Component

Use this.$emit('event_name') to send an event to the parent component.

enter image description here

Parent Component

In order to listen to that event in the parent component, we do v-on:event_name and a method (ex. handleChange) that we want to execute on that event occurs

enter image description here

Done :)


From the documentation:

In Vue.js, the parent-child component relationship can be summarized as props down, events up. The parent passes data down to the child via props, and the child sends messages to the parent via events. Let’s see how they work next.

enter image description here

How to pass props

Following is the code to pass props to a child element:

<div>
  <input v-model="parentMsg">
  <br>
  <child v-bind:my-message="parentMsg"></child>
</div>

How to emit event

HTML:

<div id="counter-event-example">
  <p>{{ total }}</p>
  <button-counter v-on:increment="incrementTotal"></button-counter>
  <button-counter v-on:increment="incrementTotal"></button-counter>
</div>

JS:

Vue.component('button-counter', {
  template: '<button v-on:click="increment">{{ counter }}</button>',
  data: function () {
    return {
      counter: 0
    }
  },
  methods: {
    increment: function () {
      this.counter += 1
      this.$emit('increment')
    }
  },
})
new Vue({
  el: '#counter-event-example',
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function () {
      this.total += 1
    }
  }
})

I don't know why, but I just successfully updated parent data with using data as object, :set & computed

Parent.vue

<!-- check inventory status - component -->
    <CheckInventory :inventory="inventory"></CheckInventory>

data() {
            return {
                inventory: {
                    status: null
                },
            }
        },

Child.vue

<div :set="checkInventory">

props: ['inventory'],

computed: {
            checkInventory() {

                this.inventory.status = "Out of stock";
                return this.inventory.status;

            },
        }

Another way is to pass a reference of your setter from the parent as a prop to the child component, similar to how they do it in React. Say, you have a method updateValue on the parent to update the value, you could instantiate the child component like so: <child :updateValue="updateValue"></child>. Then on the child you will have a corresponding prop: props: {updateValue: Function}, and in the template call the method when the input changes: <input @input="updateValue($event.target.value)">.


The way more simple is use this.$emit

Father.vue

<template>
  <div>
    <h1>{{ message }}</h1>
    <child v-on:listenerChild="listenerChild"/>
  </div>
</template>

<script>
import Child from "./Child";
export default {
  name: "Father",
  data() {
    return {
      message: "Where are you, my Child?"
    };
  },
  components: {
    Child
  },
  methods: {
    listenerChild(reply) {
      this.message = reply;
    }
  }
};
</script>

Child.vue

<template>
  <div>
    <button @click="replyDaddy">Reply Daddy</button>
  </div>
</template>

<script>
export default {
  name: "Child",
  methods: {
    replyDaddy() {
      this.$emit("listenerChild", "I'm here my Daddy!");
    }
  }
};
</script>

My full example: https://codesandbox.io/s/update-parent-property-ufj4b


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to vue.js

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Center content vertically on Vuetify Vue.js get selected option on @change Using Environment Variables with Vue.js did you register the component correctly? For recursive components, make sure to provide the "name" option Vue 'export default' vs 'new Vue' How can I go back/route-back on vue-router? Change the default base url for axios How to reference static assets within vue javascript How to change port number in vue-cli project

Examples related to vue-component

Vue 'export default' vs 'new Vue' Vuex - Computed property "name" was assigned to but it has no setter How to add external JS scripts to VueJS Components How to listen for 'props' changes How can I set selected option selected in vue.js 2? How do I format currencies in a Vue component? [Vue warn]: Property or method is not defined on the instance but referenced during render VueJs get url query Vue.js - How to properly watch for nested data Vue template or render function not defined yet I am using neither?