Usage and common scenarios of Vue custom events
Usage and common scenarios of Vue custom events
Vue.js is a popular JavaScript framework for building user interfaces. In Vue, we can implement communication between components through custom events. Custom events are one of the very useful features in Vue, allowing us to pass data between different components and trigger specific behaviors. This article will introduce the usage and common scenarios of custom events in Vue, and provide specific code examples.
1. Basic usage of custom events
In Vue, we can use the $emit method to trigger custom events. The $emit method receives two parameters. The first parameter is the name of the event to be triggered, and the second parameter is the data to be passed. Components that receive custom events need to use the v-on directive to listen for events and execute related logic when the event is triggered.
The following is a simple example that demonstrates how to trigger a custom event in the parent component and receive and handle the event in the child component:
<!-- 父组件 --> <template> <div> <button @click="triggerEvent">触发事件</button> <child-component @custom-event="handleEvent"></child-component> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, methods: { triggerEvent() { this.$emit('custom-event', 'Hello, world!'); }, handleEvent(data) { console.log(data); // 输出:Hello, world! } } } </script> <!-- 子组件 --> <template> <div> <h1 id="子组件">子组件</h1> </div> </template> <script> export default { mounted() { this.$emit('custom-event', 'Hello, world!'); } } </script>
In the above example, when " When the event button is triggered, the parent component triggers the custom event and passes the string "Hello, world!" as data. The subcomponent listens to custom events through the v-on directive and prints out the received data in the handleEvent method.
2. Common scenarios of custom events
- Communication between parent and child components
Custom events transfer data and implementation between parent and child components Communication is very convenient. The parent component can pass data to the child component through custom events, and listen to the custom events triggered by the child component to obtain the child component's data.
- Communication between sibling components
If two components do not have a parent-child relationship, but need to communicate, you can use Vue's event bus to achieve it. An event bus is an empty Vue instance used to share events between different components. Custom events can be triggered and received between different components through the $emit and $vnode.$on methods.
Here is an example that demonstrates how to use the event bus to communicate between sibling components:
<!-- 组件A --> <template> <div> <button @click="triggerEvent">触发事件</button> </div> </template> <script> import eventBus from './eventBus'; export default { methods: { triggerEvent() { eventBus.$emit('custom-event', 'Hello, world!'); } } } </script> <!-- 组件B --> <template> <div> <h1 id="组件B">组件B</h1> </div> </template> <script> import eventBus from './eventBus'; export default { mounted() { eventBus.$on('custom-event', data => { console.log(data); // 输出:Hello, world! }) } } </script> <!-- eventBus.js --> import Vue from 'vue'; const eventBus = new Vue(); export default eventBus;
In the above example, component A triggered a custom event through the event bus, and Data was passed. Component B listens to custom events through the event bus and obtains data in the callback function.
- Communication between cross-level components
Vue provides provide/inject API to achieve communication between cross-level components. By using provide in the parent component to provide data, and using inject in the descendant component to inject data, communication between components at any level is achieved.
The following is an example that demonstrates how to use provide and inject to achieve communication between cross-level components:
<!-- 父组件 --> <template> <div> <p>父组件提供的数据:{{ data }}</p> <grand-child-component></grand-child-component> </div> </template> <script> export default { provide() { return { data: 'Hello, world!' } } } </script> <!-- 子组件 --> <template> <div> <p>子组件注入的数据:{{ injectedData }}</p> <child-component></child-component> </div> </template> <script> export default { inject: ['data'], computed: { injectedData() { return this.data; } } } </script> <!-- 孙子组件 --> <template> <div> <p>孙子组件注入的数据:{{ injectedData }}</p> </div> </template> <script> export default { inject: ['data'], computed: { injectedData() { return this.data; } } } </script>
In the above example, the parent component provides the data "Hello" through provide , world!", child components and grandchild components have data injected through inject respectively and used in the template.
Summary
Custom events are a very useful feature in Vue, which can easily achieve communication between components. In Vue, we can use the $emit method to trigger custom events and listen for events through the v-on directive. Custom events are suitable for communication between parent-child components, sibling components, and cross-level components. I hope that the large number of sample codes provided in this article can help you better understand the usage and common scenarios of custom events in Vue.
The above is the detailed content of Usage and common scenarios of Vue custom events. 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

AI Hentai Generator
Generate AI Hentai for free.

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



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.

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.

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

Implement marquee/text scrolling effects in Vue, using CSS animations or third-party libraries. This article introduces how to use CSS animation: create scroll text and wrap text with <div>. Define CSS animations and set overflow: hidden, width, and animation. Define keyframes, set transform: translateX() at the beginning and end of the animation. Adjust animation properties such as duration, scroll speed, and direction.

Function interception in Vue is a technique used to limit the number of times a function is called within a specified time period and prevent performance problems. The implementation method is: import the lodash library: import { debounce } from 'lodash'; Use the debounce function to create an intercept function: const debouncedFunction = debounce(() => { / Logical / }, 500); Call the intercept function, and the control function is called at most once in 500 milliseconds.

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.
