子孙组件响应式传参之provide/inject

1. Vue 2.0

  • 类型

    • provideObject | () => Object
    • injectArray<string> | { [key: string]: string | Symbol | Object }
  • 详细

    这对选项需要一起使用,以允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深,并在其上下游关系成立的时间里始终生效。

  • 用法

    //父组件
      provide(){
        return {
          date:()=>this.date
        }
      },
    
    //孙组件
     inject: ['date'],
      computed: {
        newDate() {
          return this.date()
        }
      },

    2. Vue3.0

  • 用法
    //父组件
    <script setup>
    import { provide, ref } from 'vue'
    
    const location = ref('North Pole')
    
    function updateLocation() {
      location.value = 'South Pole'
    }
    
    provide('location', {
      location,
      updateLocation
    })
    </script>
    
    //孙组件
    <!-- 在注入方组件 -->
    <script setup>
    import { inject } from 'vue'
    
    const { location, updateLocation } = inject('location')
    </script>
    
    <template>
      <button @click="updateLocation">{{ location }}</button>
    </template>