2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Vue 3 introduced the Composition API, which brought new flexibility and power to component communication.
In front-end development, a component can be seen as an independent unit for building a user interface. It encapsulates specific functions and styles, can be reused, and can be developed and tested independently of other parts. The main role of a component is to improve the reusability, maintainability, and scalability of the code. By splitting the interface into multiple components, developers can more easily manage complex applications and can optimize each component, thereby improving overall development efficiency and application performance.
In front-end frameworks such as Vue.js, components can be nested to form a component tree. In this tree structure, each component can have subcomponents, and these subcomponents can have their own subcomponents, forming a hierarchical structure. This structure makes the relationship between components clear and easy to manage and maintain.
The concepts of component tree and parent-child component relationship are crucial to understanding component communication. Mastering these basics can help developers design and implement communication mechanisms between components more effectively.
What are props
Props is a mechanism for passing data from a parent component to a child component. In Vue 3, usedefineProps
API is used to declare receiving props, which maintains the one-way flow of data and ensures the independence and reusability of components.
How to pass props in parent component
In the parent component's template, usev-bind
or abbreviation:
To bind data:
- <template>
- <ChildComponent :my-prop="parentData" />
- </template>
here,:my-prop
Indicates that this is a dynamically bound prop.parentData
Is the data defined in the parent component。
How to receive props in child components
In the child component, usedefineProps
To declare the received props:
- <script setup>
- import { defineProps } from 'vue';
-
- const props = defineProps({
- myProp: String
- });
- </script>
exist<script setup>
In the syntax sugar,defineProps
Will automatically expose props as responsive properties of the component。
What is emit
Emit is a mechanism for child components to send messages to parent components. In Vue 3, usedefineEmits
API to declare events that can be emitted, and useemit
Function to trigger the event.
How to trigger events in child components
In the child component's method, use defineEmits
To declare events that can be emitted, and use emit
To trigger:
- <script setup>
- import { defineEmits } from 'vue';
-
- const emit = defineEmits(['my-event']);
-
- function triggerEvent() {
- emit('my-event', dataToPass);
- }
- </script>
defineEmits
Used to declare events that a component can emit, andemit
Functions are used to trigger these events.
How to listen to child component events in parent component
In the parent component's template,usev-on
or abbreviation@
To listen to events emitted by child components:
- <template>
- <ChildComponent @my-event="handleEvent" />
- //或者<ChildComponent v-on:my-event="handleEvent" />
- </template>
here,@my-event
Indicates that the monitoring subcomponent sendsmy-event
event,handleEvent
It is a method defined in the parent component. When the event is triggered, this method will be called.
Assume there is a parent componentParentComponent
and a subcomponentChildComponent
, the parent component needs to pass data to the child component, and the child component needs to notify the parent component after a specific operation.
Parent ComponentParentComponent.vue
- <template>
- <ChildComponent :my-prop="parentData" @child-event="handleChildEvent" />
- </template>
-
- <script setup>
- import { ref } from 'vue';
- import ChildComponent from './ChildComponent.vue';
-
- const parentData = ref('initial data');
- const handleChildEvent = (data) => {
- console.log('Received data from child:', data);
- };
- </script>
SubassemblyChildComponent.vue
- <template>
- <button @click="sendDataToParent">Send Data to Parent</button>
- </template>
-
- <script setup>
- import { defineProps, defineEmits } from 'vue';
-
- const props = defineProps({
- myProp: String
- });
-
- const emit = defineEmits(['child-event']);
-
- function sendDataToParent() {
- emit('child-event', props.myProp);
- }
- </script>
In this example, the parent component passes:my-prop
Pass data to child components and pass@child-event
Listen for events emitted by child components.defineProps
Receives the parent component'smyProp
and use it in button click eventemit
Send data to the parent component.
Pinia is the official recommended state management library for Vue 3. It provides a component-based way to manage application state. Here are some of the main advantages and features of Pinia:
To start using Pinia, you first need to install Pinia:
npm install pinia
Or using Yarn:
yarn add pinia
Then, set up Pinia in your Vue app:
- import { createPinia } from 'pinia';
-
- const pinia = createPinia();
- app.use(pinia);
Create a store:
- import { defineStore } from 'pinia';
-
- export const useCounterStore = defineStore('counter', () => {
- const count = ref(0);
-
- function increment() {
- count.value++;
- }
-
- return { count, increment };
- });
Use the store in your component:
- <script setup>
- import { useCounterStore } from '@/stores/counter';
-
- const counterStore = useCounterStore();
- </script>
-
- <template>
- <div>
- <p>Count: {{ counterStore.count }}</p>
- <button @click="counterStore.increment">Increment</button>
- </div>
- </template>
Pinia is very easy to integrate with components, mainly throughdefineStore
function to create a store. In the component, you can directly use the state and methods in the store:
- <template>
- <div>
- <p>Count: {{ count }}</p>
- <button @click="increment">Increment</button>
- </div>
- </template>
-
- <script setup>
- import { useCounterStore } from '@/stores/counter';
-
-
- const counterStore = useCounterStore();
- const { count, increment } = storeToRefs(counterStore);
- //如果这里不使用storeToRefs会丢失响应式特性
- </script>
In the above example, we access the template directlycount
To display the counter value, and call it in the button click eventincrement
method to increase the counter value.
Basic usage of Provide/Inject
In Vue 3,provide
andinject
It is a way of communication between parent and child components, allowing an ancestor component to inject a dependency into all its descendant components, no matter how deep the component hierarchy is.
provide
Functions provide data.inject
Function to inject data.Where to use Provide/Injectprovide
andinject
Applicable to the following scenarios:
props
When passing data.Sample Code:
- // 祖先组件
- export default {
- setup() {
- const message = 'Hello from Ancestor!';
- provide('message', message);
- }
- }
-
- // 子孙组件
- export default {
- setup() {
- const message = inject('message');
- return { message };
- }
- }
Teleport concept and purposeTeleport
It is a new built-in component added in Vue 3, which allows you to "teleport" a part of the template inside a component to any other location in the DOM.
How to use Teleport for component communicationTeleport
It is not used for communication between components, but for controlling the rendering position of components.Teleport
Renders parts of a component into the DOM of its parent component, thus enabling a special way of communication.
Sample Code:
- <!-- 父组件 -->
- <template>
- <div>
- <Teleport to="body">
- <ChildComponent />
- </Teleport>
- </div>
- </template>
-
- <!-- 子组件 -->
- <template>
- <div>Some content</div>
- </template>
Introduction to the Composition API
Vue 3 introduced the Composition API, which provides a new way to organize and reuse logic.setup
Functions allow developers to more flexibly control the responsive state and lifecycle of components.
Using ref and reactive for inter-component communicationref
andreactive
It is a tool in the Composition API for creating responsive data.
ref
Used to create responsive references of basic data types.reactive
Used to create a responsive reference to an object type.Using provide and inject in the Composition API
In the Composition API,provide
andinject
allowablesetup
Used in functions to achieve cross-component communication.
Sample Code:
- // 祖先组件
- import { provide } from 'vue';
-
- export default {
- setup() {
- const message = ref('Hello from Ancestor!');
- provide('message', message);
- }
- }
-
- // 子孙组件
- import { inject } from 'vue';
-
- export default {
- setup() {
- const message = inject('message');
- return { message };
- }
- }
Through these Vue 3-specific communication methods, developers can organize communication between components more flexibly and improve the maintainability and reusability of the code.
Vue 3 introduces the Composition API, which brings new flexibility and powerful features to component communication. Component communication is the key to building complex user interfaces in front-end development. It involves data transfer and event triggering between parent-child components, sibling components, and ancestor and descendant components. Vue 3 provides a variety of communication methods, including traditional props and emit, as well as the newly added Provide/Inject, Teleport, and Composition APIs.
Creation is not easy. If this article helps you, can you give it a thumbs up?