Home >Web Front-end >Vue.js >What is the usage of $on in vue

What is the usage of $on in vue

WBOY
WBOYOriginal
2022-03-17 11:20:5617138browse

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)".

What is the usage of $on in vue

The operating environment of this article: Windows 10 system, Vue version 2.9.6, DELL G3 computer.

What is the usage of $on in vue

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(&#39;isLeft&#39;, &#39;点击事件!&#39;);
      }
    },
    mounted() {
      this.$on(&#39;isLeft&#39;, (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(&#39;isLeft&#39;, &#39;点击事件!&#39;);
      },
      isClickOther() {
        this.$emit(&#39;isRight&#39;, [&#39;点击1&#39;, &#39;点击2&#39;]);
      }
    },
    mounted() {
      this.$on(&#39;isLeft&#39;, (val) => {
        console.log(val);
      });
      this.$on(&#39;isRight&#39;, (...val) => {
        console.log(val);
      });
      this.$on([&#39;isLeft&#39;, &#39;isRight&#39;], () => {
        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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to use v-if in vueNext article:How to use v-if in vue