1.子组件调用父组件,子组件向父组件传值
//父组件代码
<script setup>
// 引入子组件
import son from './components/son.vue'
//子组件要调用的父组件的方法
const getMessage = (msg)=>{
console.log(msg);
}
</script>
<template>
//绑定制自定义事件
<son @get-message="getMessage"></son>
</template>
//子组件代码
<script setup>
//2.使用defineEmits编译器宏函数生成emit方法
const emit = defineEmits(['get-message'])
const sendMsg =()=>{
//3.触发自定义函数
emit('get-message','this is son')
}
</script>
<template>
<div @click="sendMsg">
按钮
</div>
</template>
2.父组件向子组件传值
//父组件
<script>
//引入子组件
import son from './components/son.vue'
const mess = ref(20)
const messAdd = () => {
mess.value++
}
</script>
<template>
//1.绑定属性mess
<son :mess="mess" @click="messAdd"></son>
</template>
//子组件
<script setup>
//2.defineProps接受数据
const props = defineProps({
mess: Number,
})
</script>
<template>
<div>
父组件传入的数据:{{ props.mess }}
</div>
</template>
3.使用provide传值,用inject接收
![](https://i-blog.csdnimg.cn/blog_migrate/1b686912487dee98bb0e53024aa3282e.png)
//顶级组件
<script setup>
import { provide, reactive, ref, watch } from "vue"
//引入子组件
import son from './components/son.vue'
const mess = ref(20)
const messAdd = () => {
mess.value++
}
// 1.顶层组件提供数据
//使用provide传递参数
provide('fatherData', "我是爷爷传过来的数据")
// 顶层组件提供动态数据
provide('dongtai', mess)
//顶层把自己的方法传递出去
provide('addfather', messAdd)
</script>
<template>
<div>父亲:{{ mess }}</div>
<son></son>
</template>
<style scoped></style>
//儿子组件
<script setup>
import{inject, ref} from 'vue'
//引入子组件
import grandson from './grandson.vue'
//使用inject接收顶层传递的参数
const dongtai = inject('dongtai')
const num = ref(dongtai)
</script>
<template>
<div>儿子:{{ num }}</div>
<grandson></grandson>
</template>
<style></style>
//孙子组件
<script setup>
import { inject } from 'vue';
//使用inject接收顶层传递的参数
const geandSon = inject('fatherData')
const dongtai = inject('dongtai')
//调用顶层方法
const addfather = inject('addfather')
</script>
<template>
<div>孙子:{{ geandSon }}</div>
<div>孙子:{{ dongtai }}</div>
<bottom @click="addfather">孙子:点击把爷爷+1</bottom>
</template>
<style>
div {
font-size: 30px;
}
</style>