Vue 提供或注入
Vue 中的 Provide/Injecte(提供或注入)用于将数据从一个组件提供给其他组件,尤其是在大型项目中。
Provide(提供)使数据可用于其他组件。
Inject(注入)用于获取所提供的数据。
Provide/Inject (提供或注入)是一种共享数据的方式,可以替代使用道具传递数据。
Provide/Inject
在一个大型项目中,组件内部有组件,很难使用 props 将数据从 "App.vue" 提供给子组件,因为它需要在数据通过的每个组件中定义 props。
如果我们使用 provide/inject 而不是 props,那么我们只需要在提供数据的地方定义提供的数据,并且只需要在注入的地方定义注入的数据。
Provide Data(提供数据)
我们使用 "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>
Inject Data(注入数据)
既然 'foods' 数组是由 'App.vue' 中的 'provide' 提供的,我们可以将其包含在 'FoodKinds' 组件中。
通过将 'foods' 数据注入 'FoodKinds' 组件,我们可以使用 '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>