父组件
首先,我们创建一个父组件,名为 ParentComponent.vue
:
<template>
<div>
<h1>父组件</h1>
<p>从子组件接收到的数据:{{ receivedData }}</p>
<ChildComponent @sendData="updateData" />
</div>
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const receivedData = ref('');
function updateData(data) {
receivedData.value = data;
}
</script>
<style scoped>
/* 可选的样式部分 */
</style>
代码解释
1,在 <template> 部分,我们展示父组件的数据 receivedData,并通过自定义事件 sendData 来接收子组件传递的数据。
2,在 <script setup> 部分,我们引入了Vue3的 ref 来创建响应式变量 receivedData。
3,updateData 方法用于更新接收到的数据。
4,我们通过引入并使用子组件 ChildComponent,同时监听其 sendData 事件并调用 updateData 方法。
子组件
接下来,我们创建子组件,名为 ChildComponent.vue
:
<template>
<div>
<h2>子组件</h2>
<input v-model="inputData" placeholder="请输入数据">
<button @click="sendDataToParent">发送数据到父组件</button>
</div>
</template>
<script setup>
import { ref, defineEmits } from 'vue';
const inputData = ref('');
const emit = defineEmits(['sendData']);
function sendDataToParent() {
emit('sendData', inputData.value);
}
</script>
<style scoped>
/* 可选的样式部分 */
</style>
代码解释
1,在 <template> 部分,我们创建了一个输入框和一个按钮。
2,在 <script setup> 部分,使用 ref 创建了响应式变量 inputData,用于存储用户输入的数据。
3,通过 defineEmits 定义了 sendData 事件。
4,sendDataToParent 方法会通过 emit 函数将 inputData 变量的值发送给父组件。