第五十九:子传父 defineEmits

首先在 子组件 里面:

//子传父

//定义一个名为 emits 的对象, 用于存储自定义事件

const emits = defineEmits(["web","user"]) // 定义两个事件

//发送名为 web 和 user 的自定义事件

emits("web", {name:"邓瑞",url:"www.dengruicode.com"})

//添加用户事件的方法:userAdd

const userAdd = () => {

//发送名为 user 的自定义事件

emits("user", 10)

}

父接收子传过的数据:

//子传父 定义的两个方法

constemitsWeb= (data) => {
console.log("emitsWeb:",data)
web.url = data.url
}

constemitsUser= (data) => {
console.log("emitsUser:",data)
user.value += data
}

<template>

<!-- 子传父 -->

<Header @web="emitsWeb" @user="emitsUser" /> // 注意:这里 @web 和 @user 是父定义的两个事件

{{ web.url }} - {{ user }}

</template>

App.vue

复制代码
<script setup>
  import { reactive,ref } from 'vue'

  //导入子组件
  import Header from "./components/header.vue"

  //响应式数据
  const web = reactive({
    name: "邓瑞编程",
    url: 'dengruicode.com'
  })

  const user = ref(0)

  //子传父
  const emitsWeb = (data) => {
    console.log("emitsWeb:",data)
    web.url = data.url
  }

  const emitsUser = (data) => {
    console.log("emitsUser:",data)
    user.value += data
  }
</script>

<template>
  <!-- 子传父 -->
  <Header @web="emitsWeb" @user="emitsUser" />

  {{ web.url }} - {{ user }}
</template>

<style scoped></style>

header.vue

复制代码
<script setup>
    //子组件

    /*
        defineEmits是Vue3的编译时宏函数,
        用于子组件向父组件发送自定义事件
    */
    //子传父
    //定义一个名为 emits 的对象, 用于存储自定义事件
    const emits = defineEmits(["web","user"])
    //发送名为 web 和 user 的自定义事件
    emits("web", {name:"邓瑞",url:"www.dengruicode.com"})
    
    //添加用户
    const userAdd = () => {
        //发送名为 user 的自定义事件
        emits("user", 10)
    }
</script>

<template>
    <h3>Header</h3>

    <button @click="userAdd">添加用户</button>
</template>

<style scoped>

</style>
相关推荐
WooaiJava40 分钟前
AI 智能助手项目面试技术要点总结(前端部分)
javascript·大模型·html5
LYFlied43 分钟前
从 Vue 到 React,再到 React Native:资深前端开发者的平滑过渡指南
vue.js·react native·react.js
爱喝白开水a1 小时前
前端AI自动化测试:brower-use调研让大模型帮你做网页交互与测试
前端·人工智能·大模型·prompt·交互·agent·rag
Never_Satisfied1 小时前
在JavaScript / HTML中,关于querySelectorAll方法
开发语言·javascript·html
董世昌411 小时前
深度解析ES6 Set与Map:相同点、核心差异及实战选型
前端·javascript·es6
B站_计算机毕业设计之家1 小时前
豆瓣电影数据采集分析推荐系统 | Python Vue Flask框架 LSTM Echarts多技术融合开发 毕业设计源码 计算机
vue.js·python·机器学习·flask·echarts·lstm·推荐算法
WeiXiao_Hyy2 小时前
成为 Top 1% 的工程师
java·开发语言·javascript·经验分享·后端
吃杠碰小鸡2 小时前
高中数学-数列-导数证明
前端·数学·算法
kingwebo'sZone2 小时前
C#使用Aspose.Words把 word转成图片
前端·c#·word
xjt_09012 小时前
基于 Vue 3 构建企业级 Web Components 组件库
前端·javascript·vue.js