You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

2 D铆as
3 Hrs
17 Min
46 Seg

Provide / Inject

19/23
Resources

How to use provide and inject with the Composition API in Vue.js?

In the world of Vue.js, passing data between components can become a complicated task if you don't use the right tools. This is where provide and inject come into play, offering an elegant solution for sharing data between a component and its descendants. This mechanism avoids the need to manually pass data through each hierarchical level of a component, which could result in messy code and unnecessary props.

Implementation in Composition API

When using provide and inject with the Composition API, we must work within the setup function. This is a significant change from the Options API, as we move from JSON configurations to functions that offer greater flexibility and readability.

Create provide in the main component

  1. Configure setup: We start by creating the setup function in the main component.

    import { provide } from 'vue';
    export default { setup() { // Define the value to provide provide('username', 'DianaNerd'); } }}
  2. Define value: We use provide to set a key-value pair, where 'username' is the key to be shared with descendant components.

Receiving values in child components with inject

To receive the values provided in a child component, we use inject, which must also be called inside the setup function.

  1. Import inject: We add inject inside the import from Vue.

    import { inject } from 'vue';
    export default { setup() { // Receive the provided value const userName = inject('username');
     return { userName };} }}
  2. Access the values: we create a variable in setup that receives the injected value, so that it is available in the component's template.

Reactivity in provide and inject

It is crucial to know that, by default, using provide and inject does not generate reactivity. To achieve this behavior, you will need to use tools like ref when defining values in provide. This will allow the values to be reactive and reflect changes automatically.

import { provide, ref } from 'vue';
export default { setup() { const username = ref('DianaNerd'); provide('username', username);    
 return { username }; } }}

Advantages of using Composition API

Switching from Options API to Composition API not only improves code organization, but also significantly reduces the number of lines required to perform the same operations. This approach not only improves code readability and maintainability, but also promotes a cleaner and more functional environment in Vue.js.

Recommendations

We encourage you to practice with provide and inject, applying reactivity and creating test projects. Experiment with use cases, such as a counter, to better understand these tools and their benefits in the data flow of your components. Share it with the community to get feedback!

Contributions 7

Questions 3

Sort by:

Want to see more contributions, questions and answers from the community?

Si quieren actualizar el username desde el nieto hacia el padre as铆 como si usaramos un emit() cuando necesitamos comunicar de hijo a padre, lo hacemos de la siguiente manera:

  1. Declaramos desde el provider (padre) una variable tipo objeto que contenga la constante y el m茅todo que hace la actualizaci贸n, obviamente la constante debe ser reactiva
const username = ref('');
provide('username', { username, updateUsername });
  1. Ahora desde el inject (nieto) podemos obtener ambas variables (constante y m茅todo) y usarlas cuando querramos de la siguiiente manera
const { username, updateUsername } = inject('username');

Muy f谩cil.

para volver la variable reactiva la puse asi:

const username = ref(inject("username"));

aunque funcione no se , si sea mala practica

Para volver username reactivo, lo realic茅 volviendo reactiva la variable antes de poveerla con provide()
Archivo: App.vue

export default {
  setup() {
    const username = ref("pruebas2");
    provide("username", username);
  },
}

Provide / Inject : Es la forma de pasar props (valores) de componentes abuelos a nietos, bisnietos, tataranietos, etc. de una forma mas optima. El valor no es reactivo, es importante usar toRefs() para hacerlo reactivo.

Logr茅 hacer que cambie el valor de username, pero no se muestra el cambio en la vista, 驴por qu茅 ser谩?

<template>
  <h2>{{ fullName }}</h2>
  <h3>Username: {{ username }}</h3>
  <h3>Age: {{ age }}</h3>
</template>

<script>
import { ref, computed, inject, toRef } from "vue"

export default {
  props: {
    firstName: {
      type: String,
      default: "John",
      required: true,
    },
    lastName: {
      type: String,
      default: "Doe",
      required: true,
    }
  },

  setup(props, context) {
    console.log(context)

    const firstName = ref("Miguel")
    const lastName = ref("Reyes")

    let username = toRef(inject("username"))._object
    console.log(username)
    setTimeout(() => {
      username = "David!"
      console.log(username)
    }, 2000)
    const age = inject("age")

    return {
      fullName: computed(() => `${firstName.value} ${lastName.value}`),
      username,
      age,
    }
  }
}
</script>

<style>
</style>

vue js es p茅simo loco, wtf con este framework.

驴c貌mo se vuelve reactivo el valor inyectado? no lo explican :v