vite+ts+vue3 知识点(依赖注入provide&inject)

应用场景:

祖先级别的组件的数据有很多子组件要用的时候,可以使用依赖注入(provide&inject)的方法传递数据,这样就无需使用多次父传子的形式去传递数据,避免页面过度冗余。

基本使用

祖先组件App.vue

<template>
  <div>
    <button @click="btn">祖先修改</button>
    <Father></Father>
  </div>
</template>

<script setup lang="ts">
import { ref, provide, readonly } from 'vue';
import Father from './components/father.vue'
const colorValue = ref('red')

// 将数据定义为readonly后子组件不能修改provide的值,当前组件仍可以修改
// 提供出去
provide('color', readonly(colorValue)) 
const btn = () => {
  colorValue.value = 'blue'
}
</script>

<style scoped lang="less">

</style>

父组件Father.vue

<template>
    <div>
        <div class="divBgc">
            我是父组件
            <Son></Son>
        </div>
    </div>
</template>

<script setup lang="ts" name="Father">
import { inject, Ref } from 'vue'
import Son from '../components/son.vue'
const color = inject<Ref<string>>('color')
</script>

<style scoped lang="less">
.divBgc {
    width: 500px;
    height: 500px;
    background-color: v-bind(color);
}
</style>

子组件Son.vue

<template>
    <div>
        <div class="divBgc">我是子组件</div>
        <button @click="btn">子组件修改</button>
    </div>
</template>

<script setup lang="ts" name="Son">
import { Ref, inject } from 'vue';
// 注入进来
const colorValue = inject<Ref<string>>('color')
const btn = () => {
    // 非空断言
    colorValue!.value = 'skyblue'
}

</script>

<style scoped lang="less">
.divBgc {
    width: 200px;
    height: 200px;
    background-color: v-bind(colorValue);
}
</style>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微光无限

破晓的日子还有很多!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值