Simple Vue.js Custom Event Listenting Parent/Child with $emit

Picture shows Jason A. Martin - Software Engineer, Indie Game Developer, Tech Evangelist, Entrepreneur.

This quick article shows you how to create a custom event in a child (component) and pick it up in the main Vue instance.

Each time you click the button, the background hue (HSL) will increase by 10. Go ahead and give it some clicks!

You can ignore the way I imported the component (script type="text/x-template"). I was just messing around with different ways to attach components.

By the way, if you want to mess around on CodePen to quickly make your own Vue.JS pens, I've created a template you can fork here: https://codepen.io/jasonamartin/pen/ZJzKve

Vue/Razor Note: If you happen to be using Razor templates and are having any issues with something like: "@click" in Vue, you need to use the longform.

Example: v-on:click="whatever"

Current App Background Hue: {{ hue }}



Code

Here's the code for this example(don't forget to pull in Vue.JS dependencies):


Vue.component("hue-changer", {
  template: "#hue-changer",
  methods: {
    hueincrease: function () {
      this.$emit('hueincrease')
    }
  },
});

new Vue({ el: '#app', data: { hue: 100 }, methods: { sethue(hsl) { this.hue += 10 } } })