


An article briefly analyzing the custom events and global event bus of 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!
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:
3.2 The second method , in the parent component:
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 tutorial、web 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); }
Find the subcomponent and trigger the shanyu event on the Student component instance
Trigger the custom event: this. $emit('shanyu',data)
methods: { sendStudentName(){ //触发Student组件实例身上的shanyu事件 this.$emit('shanyu',this.name) } }
4. Unbind custom events
unbind(){ this.$off('shanyu')// 只适用于解绑1个事件 this.$off(['shanyu','demo'])// 适用于解绑多个 this.$off()// 适用于解绑全部 }
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 // 安装全局事件总线 } })
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('shanyu', (data) => { console.log("我是School组件,我收到了数据", data); }); }, //使用完之后销毁该绑定事件避免后期错误使用 beforeDestroy() { this.$bus.$off("hello") }, } </script>
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('shanyu',this.name) } }, } </script>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





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.

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.

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

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.

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.

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

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.

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.
