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>

628

被折叠的 条评论
为什么被折叠?



