房子(父组件)包含窗户和门(子组件)
窗户和门(子组件)是房子(父组件)的一部分
父组件
<!-- 父组件:比如叫 Home.vue -->
<template><div><h1>这是父组件(房子)</h1><!-- 下面这两个就是子组件,像插积木一样插在父组件里 --><WindowComponent /> <!-- 窗户组件(子组件) --><DoorComponent /> <!-- 门组件(子组件) --></div>
</template>
子组件
<!-- 子组件1:WindowComponent.vue(窗户) -->
<template><div>我是窗户(子组件)</div>
</template><!-- 子组件2:DoorComponent.vue(门) -->
<template><div>我是门(子组件)</div>
</template>
父组件给子组件传数据(父→子)
比如父组件有一个 "苹果",想递给子组件:
<!-- 父组件(Parent.vue) -->
<template><!-- 用 :苹果="我的苹果" 把数据传给子组件 --><ChildComponent :苹果="我的苹果" />
</template><script setup>
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'// 父组件的苹果
const 我的苹果 = ref('红苹果')
</script>
子组件
<!-- 子组件(ChildComponent.vue) -->
<template><p>收到父组件的苹果:{{ 苹果 }}</p>
</template><script setup>
// 声明要接收父组件的"苹果"
const props = defineProps(['苹果'])
</script>
父组件用 :属性名="数据" 传数据
子组件用 defineProps 声明接收
子组件给父组件传数据(子→父)
比如子组件想告诉父组件 "苹果吃完了":
<!-- 子组件(ChildComponent.vue) -->
<template><!-- 点击按钮时,给父组件发消息 --><button @click="$emit('告诉父组件', '苹果吃完了')">告诉父组件</button>
</template><script setup>
// 声明要发的消息名称
defineEmits(['告诉父组件'])
</script>
父组件
<!-- 父组件(Parent.vue) -->
<template><!-- 监听子组件的消息,收到后执行处理函数 --><ChildComponent @告诉父组件="处理消息" /><p>子组件说:{{ 子组件消息 }}</p>
</template><script setup>
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'const 子组件消息 = ref('')// 处理子组件发来的消息
const 处理消息 = (消息内容) => {子组件消息.value = 消息内容
}
</script>
子组件用 $emit('消息名', 内容) 发消息
父组件用 @消息名="处理函数" 接收消息