CodeOrc.com - Learn by example
X
Make an RPG
Vue Implementations

Example of How to pass data to parent component

So, you have a component and you need to pass data up to it's parent. How do you do it?

You need 2 things:

  • 1. Use $emit to call an event.
  • 2. You can then respond to that event in the HTML markup where the component is embedded with v-on.

<div id="app" v-bind:style=" { color: myColor }"> test <entry v-on:changecol= 'myColor="blue";'></entry> </div>
Vue.component("entry", { template: `<input type="button" value="change color" @click='$emit("changecol")'> </input>` }); var app = new Vue({ el: "#app", data: { myColor: "red" } });
DO IT

In the v-on handler you can write code or use a function. Let's see what it looks like if we call another function instead of setting the color directly:

<div id="app" v-bind:style="{ color: myColor }"> test <entry v-on:changecol="change2" > </entry> </div>
Vue.component("entry", { template: `<input type="button" value="change color" @click='$emit("changecol")'> </input>` }); var app = new Vue({ el: "#app", data: { myColor: "red" }, methods: { change2: function() { this.myColor = "green"; } } });
DO IT

The only difference here is that we're calling the function change2, instead of directly embedding code.

In the next lesson, we will learn about Example of How to use v-bind:is in Dynamic Components

Get the Latest Tutorial Updates
<< >>
X