Vue Provide/Inject
Vue 中的 Provide/Inject 用於將資料從一個元件提供給其他元件,尤其是在大型專案中。
Provide 使資料可供其他元件使用。
Inject 用於獲取提供的資料。
Provide/Inject 是一種共享資料的方式,可以替代使用 props 傳遞資料。
Provide/Inject
在大型專案中,隨著元件巢狀層級加深,使用 props 將資料從 "App.vue" 傳遞到子元件可能會變得困難,因為它要求在資料經過的每個元件中都定義 props。
如果我們使用 provide/inject 替代 props,我們只需要在提供資料的元件中定義提供的資料,並在注入資料的元件中定義注入的資料。
提供資料
我們使用 'provide' 配置選項來使資料可供其他元件使用。
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>
在上面的程式碼中,'foods' 陣列現在被提供了,以便它可以在您的專案中的其他元件中被注入。
注入資料
既然 'foods' 陣列已經在 'App.vue' 中透過 'provide' 提供了,我們就可以在 'FoodKinds' 元件中包含它。
透過在 'FoodKinds' 元件中注入 'foods' 資料,我們可以使用 App.vue 中的資料在 'FoodKinds' 元件中顯示不同的食物。
示例
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>
執行示例 »