zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    好玩夫妻
    笔记整理MS SQL2005 中查询表的字段信息,
    庆幸也与你逛过那一段旅程
    PureMVC
    简单工厂模式
    工厂方法模式
    UML类图
    PureMVC
    oracle双机热备
    一个不错的免费网络硬盘
  • 原文地址:https://www.cnblogs.com/chenzxl/p/14441808.html
Copyright © 2011-2022 走看看