Home > Web Front-end > Vue.js > Provide and inject functions in Vue3: efficient data transfer between components

Provide and inject functions in Vue3: efficient data transfer between components

WBOY
Release: 2023-06-18 20:45:08
Original
1820 people have browsed it

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.

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

  1. 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'
  }
})
Copy after login

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'
  }
}
Copy after login

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.

  1. 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')
Copy after login

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template