Friday, May 4, 2018

[Vue.js][Example] An example using global event bus with vue-cli

This created a customed event named EVENT_NAME, and pass value 1233 from Student component to App component .

main.js
import Vue from 'vue'
import App from './App.vue'
import Student from './Student.vue'

const EventBus = new Vue();
export default EventBus;

Vue.component("student",Student);

new Vue({
  el: '#app',
  render: h => h(App)
})
App.vue
<template>
<student></student>
</template>

<script>
import Vue from 'vue';
import EventBus from './main.js';

export default {
mounted () {
EventBus.$on('EVENT_NAME', function (payLoad) {
alert("worked!"+payLoad);
});
}
}
</script>
Student.vue
<template>
<button @click="emitMethod">Click</button>
</template>

<script>
import Vue from 'vue';
import EventBus from './main.js';

export default {
methods: {
emitMethod () {
EventBus.$emit('EVENT_NAME', 1233);
}
}
}
</script>

Result 


No comments :

Post a Comment