Home >Web Front-end >Vue.js >What is the usage of $on in vue
In vue, "$on" is used to listen to custom events on the current instance. The event can be triggered by "vm.$emit". The callback function will receive all additional parameters passed in to the event triggering function. The syntax is "vm.$on(event, callback)".
The operating environment of this article: Windows 10 system, Vue version 2.9.6, DELL G3 computer.
Use $on(eventName) in vue to listen for events
$on(eventName) to listen for custom events on the current instance. Events can be triggered by vm.$emit. The callback function receives any additional parameters passed into the event triggering function.
vm.$on( event, callback )
Parameters:
{string | Array} event (Array is only supported in 2.2.0) {Function} callback
Instance 1 Single event on this page
<template> <section> <h1>left</h1> <el-button type="primary" @click="isClick">点击</el-button> </section> </template> <script> export default { methods: { isClick() { this.$emit('isLeft', '点击事件!'); } }, mounted() { this.$on('isLeft', (val) => { console.log(val); }); } } </script>
The above code is through the click event of the button, then this.$emit passes the event, and then this.$on captures the event of this page
Example 2 Multiple events of this page
<template> <section> <h1>left</h1> <el-button type="primary" @click="isClick">点击</el-button> <el-button type="primary" @click="isClickOther">点击</el-button> </section> </template> <script> export default { methods: { isClick() { this.$emit('isLeft', '点击事件!'); }, isClickOther() { this.$emit('isRight', ['点击1', '点击2']); } }, mounted() { this.$on('isLeft', (val) => { console.log(val); }); this.$on('isRight', (...val) => { console.log(val); }); this.$on(['isLeft', 'isRight'], () => { console.log(666); }); } } </script>
The above examples are two click events on this page. You can listen to two events at the same time, and you can also pass multiple parameters at the same time
[Related recommendations: "vue.js tutorial" 】
The above is the detailed content of What is the usage of $on in vue. For more information, please follow other related articles on the PHP Chinese website!