25、Vue3 提供 / 注入(provide/inject)

场景:当我们需要将数据从父组件传递到子组件时,通过props,但是如果有深嵌套的组件,再使用prop 传递到整个组件链中,会很麻烦

Vue3中 提供了provide 和 inject , 父组件可以作为其所有子组件的依赖项提供程序,而不管组件层次结构有多深。这个特性有两个部分:父组件有一个 provide 选项来提供数据,子组件有一个 inject 选项来开始使用这个数据。

特点:

  • 父组件不需要知道哪些子组件使用它提供的 property
  • 子组件不需要知道 inject property 来自哪里
  • 如果需要属性响应式,通过computed处理

案例

  • src/components/inject.vue
<template>
  <div>
        inject1:
      <injectcmp/>
  </div>
</template>

<script>
import injectcmp from './inject2.vue'

export default {
    components: {
        injectcmp
    },
    // 注入祖父级属性
    inject: ['username'],
    created(){
        console.log('username === ', this.username);
    }
}
</script>
  • src/components/inject2.vue
<template>
  <div>
      inject2:
      <!-- 
          非响应式属性
          数组长度:{{listlen}} -->
        <!-- 响应式属性 -->
      数组长度:{{listlen.value}}
  </div>
</template>

<script>
export default {
    //  注入祖父级属性
    inject: ['username', 'listlen'],
    created(){
        console.log('username2 === ', this.username, this.listlen);
    }
}
</script>
  • demo.vue
<!--  -->
<template>
    当前数组长度:{{list.length}}
    <injectcmp/>
    <br>
    <button @click="btnclick">改变数组长度</button>
</template>

<script>
import injectcmp from'/@/components/inject.vue'
import { computed } from 'vue'


export default {
    components: {
        injectcmp
    },
    // 不能使用this对象
    // provide: {
    //     username: 'uservalue'
    // },
    // 可以使用this对象
    provide(){
        return {
            username: 'uservalue',
            // 非响应式属性
            // listlen: this.list.length
            // 响应式属性
            listlen: computed(()=>this.list.length)
        }
    },
    methods: {
        btnclick(){
            this.list.push(6)
        }
    },
    data () {
        return {
            list: [1,2,3,4,5]
        }
    }
}

</script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容