vue3父子组件传值
父 → 子:props
父组件
<template><ChildComponent :message="parentMessage" :user="user" />
</template><script setup>
import ChildComponent from './ChildComponent.vue';
const parentMessage = 'Hello from parent';
const user = { name: 'Alice', age: 25 };
</script>
子组件
<template><p>{{ message }}</p><p>{{ user.name }} - {{ user.age }}</p>
</template><script setup>
// 声明 props
const props = defineProps({message: {type: String,required: true},user: {type: Object,required: true}
});
</script>
子 → 父:emit 事件
<template><button @click="sendToParent">Send to Parent</button>
</template><script setup>
const emit = defineEmits(['send-data']);function sendToParent() {emit('send-data', 'Data from child');
}
</script>
父组件
<template><ChildComponent @send-data="handleChildData" />
</template><script setup>
import ChildComponent from './ChildComponent.vue';function handleChildData(data) {console.log('Received:', data); // 输出 "Received: Data from child"
}
</script>