• vue3-provide/inject 注入


    为深度嵌套的组件,父组件provide提供数据来源,子组件inject开始使用这个数据

    provide: {
        todoLength: this.todos.length // 将会导致错误 'Cannot read property 'length' of undefined`
    },
    //要访问组件实例,需要将provide转换为返回对象函数
    provide() {
        return {
          todoLength: this.todos.length
        }
      },

    setup中使用

    import { provide } from 'vue' //显式导入
    import MyMarker from './MyMarker.vue
    
    export default {
      components: {
        MyMarker
      },
      setup() {
        provide('location', 'North Pole')
        provide('geolocation', {
          longitude: 90,
          latitude: 135
        })
      }
    }
    //使用
    <script>
    import { inject } from 'vue'
    
    export default {
      setup() {
        const userLocation = inject('location', 'The Universe')
        const userGeolocation = inject('geolocation')
    
        return {
          userLocation,
          userGeolocation
        }
      }
    }
    </script>
    //增加响应,使用ref, reactive 如果任何一个属性发生变化,该MyMarker组件也将自动更新
    <!-- src/components/MyMap.vue -->
    <template>
      <MyMarker />
    </template>
    
    <script>
    import { provide, reactive, ref } from 'vue'
    import MyMarker from './MyMarker.vue
    
    export default {
      components: {
        MyMarker
      },
      setup() {
        const location = ref('North Pole')
        const geolocation = reactive({
          longitude: 90,
          latitude: 135
        })
    
        provide('location', location)
        provide('geolocation', geolocation)
      }
    }
    </script>
  • 相关阅读:
    麦肯锡矩阵导航图
    以业务为核心的云原生体系建设
    万字长文拿下HTTP
    人人都该懂的埋点知识
    淘宝的技术架构
    五步,快速理解一个行业
    一文读懂用户分层
    python13day
    python12day
    python11day
  • 原文地址:https://www.cnblogs.com/chenzxl/p/14441808.html
Copyright © 2020-2023  润新知