vue3 中 inject,provide 组件传值

Father.vue

<template>
  <div class="father">
    <h3>父组件</h3>
    <h4>银子:{{ money }}</h4>
    <h4>车子:一辆{{ car.brand }}车,价值{{car.price}}万元。</h4>
    <Child></Child>
  </div>
</template>

<script lang="ts" name="Father" setup>
import { ref, reactive, provide} from "vue";
import Child from "./Child.vue";

const car = reactive({
  brand: "保时捷",
  price: 1000000,
});
const money = ref(100000);

// 向其它组件提供数据
provide("moneyContext", {money, updateMoney});
provide("car", car);

function updateMoney(value:number) {
  money.value = money.value - value;
}


</script>

<style scoped>
.father {
  background-color: rgb(165, 164, 164);
  padding: 20px;
  border-radius: 10px;
}
</style>

Child.vue

<template>
  <div class="child">
    <h3>子组件</h3>
    <GrandChild></GrandChild>
  </div>
</template>

<script lang="ts" name="Child" setup>
import { ref } from "vue";
import GrandChild from './GrandChild.vue'
// 数据
let toy = ref("奥特曼");

</script>

<style scoped>
.child {
  margin-top: 10px;
  background-color: skyblue;
  padding: 10px;
  box-shadow: 0 0 10px black;
  border-radius: 10px;
}
</style>

GrandChild.vue

<template>
  <div class="grandChild">
    <h3>孙组件</h3>
    <h4>银子:{{ money }}</h4>
    <h4>车子:一辆{{ car.brand }}车,价值{{ car.price }}万元。</h4>
    <button @click="updateMoney(100)">更新银子</button>
  </div>
</template>

<script lang="ts" name="GrandChild" setup>
import { ref, inject } from "vue";

let {money, updateMoney} = inject("moneyContext",{money: 0, updateMoney: (param:number) => {}});

let car = inject("car",{ brand: "未知", price: 0 });

</script>

<style scoped>
.grandChild {
  margin-top: 10px;
  background-color: rgb(239, 166, 37);
  padding: 10px;
  box-shadow: 0 0 10px black;
  border-radius: 10px;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值