vue3中子向父传数据

父组件

首先,我们创建一个父组件,名为 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 变量的值发送给父组件。

相关推荐
mCell8 小时前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip8 小时前
Node.js 子进程:child_process
前端·javascript
excel11 小时前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel12 小时前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼13 小时前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping13 小时前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙14 小时前
[译] Composition in CSS
前端·css
白水清风14 小时前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix15 小时前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts
用户221520442780015 小时前
new、原型和原型链浅析
前端·javascript