


Provide and inject functions in Vue3: efficient data transfer between components
The provide and inject functions in Vue3 have become the preferred solution for efficient data transfer between components. They use a new mechanism to allow child components to obtain data in ancestor components and at the same time update data in ancestor components in parent components, which provides unlimited possibilities for building complex and flexible applications. This article will discuss the provide and inject functions in Vue3 in depth to help readers better understand their working principles and usage.
- What are the provide and inject functions?
The provide and inject functions are new features in Vue3. They provide a data transfer method different from props and $emit. The provide function is used to provide data, and the inject function is used to inject data. The provide function receives an object as a parameter, which contains the data that needs to be provided to the child component. The inject function receives an array or object as a parameter. This array or object contains the data that needs to be injected from the ancestor component. It should be noted that the provide and inject functions can only pass data between the same ancestor component and descendant components, and cannot pass across components.
- How the provide and inject functions work
In Vue3, the provide and inject functions use a new mechanism to achieve data transfer. This mechanism is based on Vue's custom render function, which allows the use of the new context API to provide and inject data.
In the provide function, we can provide data by setting the provide attribute, for example:
const app = createApp({ provide: { data: 'this is data' } })
In this example, we provide a data in the root component named data, which The value is 'this is data'. Next, we can use the inject function in the subcomponent to inject this data:
const childComponent = { inject: ['data'], mounted() { console.log(this.data)//输出'this is data' } }
In the subcomponent, we inject data through the inject attribute. This attribute needs to contain the name of the data that needs to be injected, for example here We injected data named data. In the child component, we can access the injected data just like props.
It should be noted that if the inject function is used in a child component, but the provide function does not provide the data that needs to be injected, then the injected data will be undefined.
- How to use the provide and inject functions
When using the provide and inject functions, we need to pay attention to the following points:
(1)provide The inject function can only pass data between the same ancestor component and descendant components, and cannot pass it across components.
(2) The data provided in the provide function can be of any type, including functions, objects, etc.
(3) The data injected using the inject function is read-only by default, that is, the data in the ancestor component cannot be changed in the child component. If you want to change the data in the ancestor component, you need to provide a method in the ancestor component and call the method in the child component to update the data.
(4) When implementing the provide and inject functions, we can use the Symbol type to provide or inject data, which can prevent the data from being accidentally modified.
(5) When using provide to provide data, we can use the ref or reactive function in the setup function to create responsive data, so that the data can be used directly in the sub-component and can automatically respond to data changes.
The following is a complete use case, which implements a simple TodoList and uses the provide and inject functions to transfer data:
const todoListProvide = { todos: ref([ { id: 1, text: 'todo 1', done: false }, { id: 2, text: 'todo 2', done: true }, { id: 3, text: 'todo 3', done: false } ]), addTodo (text) { this.todos.push({ id: this.todos.length + 1, text: text, done: false }) } } const todoItemInject = ['todos'] const TodoItem = { inject: todoItemInject, props: { todo: { type: Object, required: true } }, methods: { toggleTodo () { this.todo.done = !this.todo.done } }, template: ` <li> {{ todo.text }} <button @click="toggleTodo">{{ todo.done ? 'Undo' : 'Done' }}</button> </li> ` } const TodoList = { provide: todoListProvide, components: { TodoItem }, setup() { const newTodo = ref('') const addTodo = () => { if (newTodo.value.trim() !== '') { todoListProvide.addTodo.call(todoListProvide, newTodo.value) newTodo.value = '' } } return { newTodo, addTodo } }, template: ` <div> <ul> <todo-item v-for="todo in todos" :key="todo.id" :todo="todo"/> </ul> <div> <input type="text" v-model="newTodo"> <button @click="addTodo">Add Todo</button> </div> </div> ` } createApp({ components: { TodoList }, template: ` <todo-list></todo-list> ` }).mount('#app')
In this case, we define a TodoList component, in this component, the provide function is used to provide two data of todos and addTodo methods. Among them, todos is a responsive array used to store all todo information, and the addTodo method is used to add a new todo. In the subcomponent TodoItem, we use the inject function to inject todos data, and use the props attribute to receive the passed todo data. In this component, we define the toggleTodo method to update the done state in todo, and then use todo's text, done attributes and toggleTodo method in the template. Finally, we create a root component and insert the TodoList into the root component for rendering.
Through the demonstration of this case, we can see how to use the provide and inject functions to achieve efficient data transfer between components. Whether we are developing simple small components or building complex and flexible applications, using the provide and inject functions allows us to better organize components and improve development efficiency.
The above is the detailed content of Provide and inject functions in Vue3: efficient data transfer between 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.

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

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.

There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.
