在 Vue 3 中,你可以使用 Composition API 和 <script setup> 来实现父组件向子组件传递数据。下面是一个使用 Composition API 和 <script setup> 的示例:
child组件
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script setup>
const props = defineProps({
message:String
})
</script>
<style lang="scss" scoped>
</style>
parent组件
<template>
<div>
<button @click="handleClick">点我父传子</button>
<ChildComponent :message="messageFromParent"></ChildComponent>
</div>
</template>
<script setup>
import ChildComponent from './父传子/ChildComponent.vue';
import { ref } from 'vue';
const messageFromParent = ref("")
const handleClick = () => {
messageFromParent.value = "Hello from the parent component"
}
</script>
效果: