07.组件间通信-provide-inject(祖孙通信)

组件间通信-provide-inject(祖孙通信)
父组件:

<template>
  <div class="father">
    <h3>父组件</h3>
    <h4>银子:{{ money }}万元</h4>
    <h4>车子:一辆{{car.brand}}车,价值{{car.price}}万元</h4>
    <Child/>
  </div>
</template>
<script setup lang="ts" name="Father">
  import Child from './Child.vue'
  import {ref,reactive,provide} from 'vue'
  let money = ref(100)
  let car = reactive({
    brand:'奔驰',
    price:100
  })
  function updateMoney(value:number){
    money.value -= value
  }
  // 向后代提供数据
  provide('moneyContext',{money,updateMoney})
  provide('car',car)
</script>
<style scoped>
  .father {
    background-color: rgb(165, 164, 164);
    padding: 20px;
    border-radius: 10px;
  }
</style>

子组件:

<template>
  <div class="child">
    <h3>我是子组件</h3>
    <GrandChild/>
  </div>
</template>
<script setup lang="ts" name="Child">
  import GrandChild from './GrandChild.vue'
</script>
<style scoped>
  .child {
    margin-top: 20px;
    background-color: skyblue;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 0 10px black;
  }
</style>

孙组件:

<template>
  <div class="grand-child">
    <h3>我是孙组件</h3>
    <h4>银子:{{ money }}</h4>
    <h4>车子:一辆{{car.brand}}车,价值{{car.price}}万元</h4>
    <button @click="updateMoney(6)">花爷爷的钱</button>
  </div>
</template>
<script setup lang="ts" name="GrandChild">
  import { inject } from "vue";
  let {money,updateMoney} = inject('moneyContext',{money:0,updateMoney:(param:number)=>{}})
  let car = inject('car',{brand:'未知',price:0})
</script>
<style scoped>
  .grand-child{
    background-color: orange;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 0 10px black;
  }
</style>

最近更新

  1. TCP协议是安全的吗?

    2024-06-09 17:24:08       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-09 17:24:08       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-09 17:24:08       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-09 17:24:08       20 阅读

热门阅读

  1. 常见知识点总结

    2024-06-09 17:24:08       13 阅读
  2. 列表的C++实

    2024-06-09 17:24:08       11 阅读
  3. JZ2440笔记:热插拔驱动

    2024-06-09 17:24:08       9 阅读
  4. 相同的树-力扣

    2024-06-09 17:24:08       13 阅读
  5. TypeScript常见面试题第十一节

    2024-06-09 17:24:08       7 阅读
  6. TalkingData数据统计:洞察数字世界的关键工具

    2024-06-09 17:24:08       10 阅读
  7. Django中drf动态过滤查询

    2024-06-09 17:24:08       11 阅读
  8. 006 RabbitMQ

    2024-06-09 17:24:08       13 阅读