Table of Contents
1. Custom events
2. Global event bus
1. Receive data
2. Provide data
Home Web Front-end Vue.js An article briefly analyzing the custom events and global event bus of Vue components

An article briefly analyzing the custom events and global event bus of Vue components

Jan 30, 2023 pm 08:19 PM
vue components

This article will introduce you to the Vue component and introduce the custom events and global event bus of the Vue component. I hope it will be helpful to you!

An article briefly analyzing the custom events and global event bus of Vue components

1. Custom events

1. What are custom events

Custom events are a method of communication between components, applicable to child components -> parent components transmit data, etc.

2. Where to use

If App is the parent component and School is a child component, and School wants to transfer data to App, then it is necessary to bind a custom event to School in App (the callback of the event is in App), that is, the parent component A self-defined event must be bound in advance for the use of sub-components, so that the data communication between father and son can be completed.

It’s like Little A’s father working out of town, and then Little A misses his father, and then what? His father gave Little A a call in advance and told Little A to make this call if he missed me. Then Little A could communicate with his father after making the call. The call was a custom event of the parent component. callback, so the data can be passed to the parent component

3. Bind custom events

3.1 The first way, in the parent component in: or

An article briefly analyzing the custom events and global event bus of Vue components

3.2 The second method , in the parent component:mounted(){this . $refs. xxx. $on('shanyu' ,this. test)}

An article briefly analyzing the custom events and global event bus of Vue components

If you write a native event in a custom event, it will default to the custom event, so we use @xxx.native to solve this problem [Related recommendations: vuejs video tutorialweb front-end development

First write a custom component in the parent component (if you want the custom event to be triggered only once, you can use once modifier, or $once method)

      // 在父组件内自定义个事件
    getMyStudent(name) {
      console.log("App收到学校名:", name);
      this.studentName = name;
    }
  },
  mounted() {
    this.$refs.student.$on("shanyu", this.getMyStudent);
  }
Copy after login

Find the subcomponent and trigger the shanyu event on the Student component instance

An article briefly analyzing the custom events and global event bus of Vue components

Trigger the custom event: this. $emit('shanyu',data)

    methods: {
        sendStudentName(){
            //触发Student组件实例身上的shanyu事件
            this.$emit('shanyu',this.name)
        }
    }
Copy after login

4. Unbind custom events

    unbind(){
        this.$off('shanyu')// 只适用于解绑1个事件
        this.$off(['shanyu','demo'])// 适用于解绑多个
        this.$off()// 适用于解绑全部
    }
Copy after login

Note: Pass this. $refs. xxx. When $on('shanyu', callback) binds a custom event, the callback must be configured in methods or use an arrow function, otherwise there will be problems with this pointing, causing Vue to report an error

2. Global event bus

1. What is the global event bus

A method of communication between components, suitable for any Communication between components. Like custom events but far more than custom events, it can realize communication between brothers

2. How to use

The main thing here is It involves three files, main.js and two brother components. First, find main.js, which is the file with vm, and then install the global event bus in the vue instance. Then why should it be placed in the beforeCreate hook? Because the characteristic of the beforeCreate statement cycle hook is that it is executed before the data is refreshed. $bus is the vm of the current application. Bus not only means bus but also bus.

new Vue({
  el: "#app",
  render: h => h(App),
  // 使用beforCreate这生命周期钩子来进行兄弟间的通信
  beforeCreate() {
    Vue.prototype.$bus = this // 安装全局事件总线
  }
})
Copy after login

3. Using event bus

1. Receive data

If component A wants to receive data, bind a custom event to $bus in component A , the event callback remains in the A component itself. methods(){mounted() {this . $bus . $on( 'xxxx' ,this . demo)}

<script>
export default {
  name: "School",
  data() {
    return {
      name: "山鱼特效屋",
      address: "南京北城区"
    };
  },
  mounted() {
    this.$bus.$on(&#39;shanyu&#39;, (data) => {
      console.log("我是School组件,我收到了数据", data);
    });
  },
  //使用完之后销毁该绑定事件避免后期错误使用
  beforeDestroy() {
    this.$bus.$off("hello")
  },
}
</script>
Copy after login

2. Provide data

this. $bus.$emit('xxxx', transmit data)

<template>
  <div class="demo">
    <h2>学生姓名:{{name}}</h2>
    <h2>学生性别:{{sex}}</h2>
    <button @click="snedStudentName">点击将数据给兄弟School</button>
  </div>
</template>

<script>
export default {
  name: "Student",
  data() {
    return {
      name: "张三",
      sex: "男"
    };
  },
  // 配置一个methods项
  methods: {
      snedStudentName(){
      // 选择给谁提供数据
          this.$bus.$emit(&#39;shanyu&#39;,this.name)
      }
  },
}
</script>
Copy after login

Note: It is best to use $off in the beforeDestroy hook to unbind the events used by the current component.

(Learning video sharing: vuejs introductory tutorial, Basic programming video)

The above is the detailed content of An article briefly analyzing the custom events and global event bus of Vue components. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

How to jump a tag to vue How to jump a tag to vue Apr 08, 2025 am 09:24 AM

The methods to implement the jump of a tag in Vue include: using the a tag in the HTML template to specify the href attribute. Use the router-link component of Vue routing. Use this.$router.push() method in JavaScript. Parameters can be passed through the query parameter and routes are configured in the router options for dynamic jumps.

See all articles