loading

Vue Provide/Inject

Data can be provided from one component to another using Vue’s Provide/Inject function, especially in larger projects.

Provide allows other components to access data.

To retrieve the given data, utilize inject.

As an alternative to sharing data using props, you can share data by utilizing the Provide/Inject method.

Provide/Inject

It can be challenging to use props to transfer data from “App.vue” to a sub-component in a large project with components inside components since each component the data passes through needs to have its props set.

The provided data must only be defined where it is provided, and the injected data must only be defined where it is injected, if provide/inject is used in place of props.

Provide Data

In order to make data accessible to other components, we utilize the ‘supply’ configuration option:

Example

App.vue:

				
					<template>
  <h1>Food</h1>
  <div @click="this.activeComp = 'food-about'" class="divBtn">About</div>
  <div @click="this.activeComp = 'food-kinds'" class="divBtn">Kinds</div>
  <div id="divComp">
    <component :is="activeComp"></component>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeComp: 'food-about',
      foods: [
        { name: 'Pizza', imgUrl: '/img_pizza.svg' },
        { name: 'Apple', imgUrl: '/img_apple.svg' },
        { name: 'Cake', imgUrl: '/img_cake.svg' },
        { name: 'Fish', imgUrl: '/img_fish.svg' },
        { name: 'Rice', imgUrl: '/img_rice.svg' }
      ]
    }
  },
  provide() {
    return {
      foods: this.foods
    }
  }
}
</script>
				
			

The ‘foods’ array is now provided in the code above so that it may be injected into other project components.

Inject Data

We can now include the ‘foods’ array in the ‘FoodKinds’ component since ‘provide’ in ‘App.vue’ has made it available.

We can utilize the data from App.vue to display various foods in the ‘FoodKinds’ component after injecting the ‘foods’ data into it:

Example

FoodKinds.vue:

				
					<template>
    <h2>Different Kinds of Food</h2>
    <p><mark>In this application, food data is provided in "App.vue", and injected in the "FoodKinds.vue" component so that it can be shown here:</mark></p>
    <div v-for="x in foods">
        <img :src="x.imgUrl">
        <p class="pName">{{ x.name }}</p>
    </div>
</template>

<script>
export default {
    inject: ['foods']
}
</script>

<style scoped>
    div {
        margin: 10px;
        padding: 10px;
        display: inline-block;
        width: 80px;
        background-color: #28e49f47;
        border-radius: 10px;
    }
    .pName {
        text-align: center;
    }
    img {
        width: 100%;
    }
</style>
				
			
Share this Doc

Vue Provide/Inject

Or copy link

Explore Topic