第五十九:子传父 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>
相关推荐
zzzzzz31017 分钟前
react-bits:从 36K Stars 的组件库,看动画交互组件该如何被评估
前端·react.js·动效
Setsuna_F_Seiei7 小时前
前端的 AI 学习之路 01 之 Agent API 调用 - 和 Agent 的基础对话
前端·人工智能·ai编程
threerocks8 小时前
AI 原生软件开发生命周期手册 - 如何借助 AI,逐阶段改造软件开发生命周期
前端·javascript·后端
徐小夕8 小时前
3分钟从想法到Agent上线:我们开源了一款AI可视化工作流“IDE”
前端·算法·github
ly768910 小时前
JavaScript 从入门到进阶:核心语法、异步编程与工程化实践
开发语言·javascript·ecmascript
why技术10 小时前
eli5,我觉得这个全网在吹的技能,使用体验真的很一般啊。
前端·人工智能·后端
excel10 小时前
记录升级 nuxt3 到 nuxt4 记录
前端
剑胆琴心静水深流11 小时前
全栈之路6---web集成与呈现
前端·vue.js·spring boot·分布式·spring·前端框架·npm
前端snow11 小时前
ai agent -- Memory汇总
前端
ITresearchGuest11 小时前
AI 焦虑下,前端该何去何从
前端·人工智能