父组件提供数据 provide
子组件获取数据 inject
第一种父传子
父组件
<template>
<div class="parent">money:{{ money }}</div>
<child/>
</template>
<script setup>
import {ref,provide} from 'vue'
import Child from './child.vue'
const money = ref(100)
provide('setmoney',money)
</script>
子组件
<template>
<div>孩子</div>
获取父亲的钱:{{ money }}
</template>
<script setup>
import { ref, inject } from "vue";
const money = ref()
money.value = inject("setmoney");
</script>
第二种 子传父,函数的方法
父组件
<template>
<div class="parent">a:{{ a }}</div>
<h2>父组件传值</h2>
钱:{{ money }}
</template>
<script setup>
import { ref, provide } from "vue";
import child from "./components/child.vue";
const a = ref(1);
function setMony(val) {
console.log(val);
}
const money = ref(100);
provide("name", { a: a, setMony });
provide("money", money);
</script>
子组件
<template>
<div>孩子</div>
{{ name.a }}
<button @click="name.setMony(6)">点击传给父亲</button>
父亲给的钱:{{ money }}
</template>
<script setup>
import { ref, onMounted, inject } from "vue";
const name = ref();
name.value = inject("name");
console.log("name", name);
const money = ref();
money.value = inject("money");
onMounted(() => {});
</script>
注:引用尚硅谷张天禹老师笔记

731

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



