Vue 提供/注入

提供/注入Vue 中用于将数据从一个组件提供给其他组件,特别是在大型项目中。

提供使数据可供其他组件使用。

注入用于获取提供的数据。

提供/注入是一种共享数据的方法,作为使用 props 传递数据的替代方法。

提供/注入

在组件内部有组件的大型项目中,很难使用 props 将 "App.vue" 中的数据提供给子组件,因为它需要在数据传递的每个组件中定义 props。

如果我们使用provide/inject而不是props,我们只需要在提供的地方定义提供的数据,也只需要在注入的地方定义注入的数据。


提供数据

我们使用“提供”配置选项使数据可供其他组件使用:

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”数组,以便可以将其注入到项目中的其他组件中。


注入数据

现在“App.vue”中的“provide”提供了“foods”数组,我们可以将其包含在“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>
运行示例 »

Vue练习

通过练习测试一下

练习:

下面的代码中需要哪个配置选项才能使鱼名“Turbot”可供其他组件使用?

data() {
  return {
    fishName: 'Turbot',
    count: 4
  }
},
() {
  return {
    fishName: this.fishName
  }
}

开始练习