第五十九:子传父 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>
相关推荐
lichenyang4537 分钟前
鸿蒙元服务跳转 H5 太慢?从 Web 内核预热、网络预连接到骨架屏的完整优化方案
前端
aa小小15 分钟前
大屏的数据应该怎么做“实时更新“?大屏页面如果一直开着不关(比如挂了几天几夜),你觉得可能会出现什么问题,需要怎么预防?
前端·数据可视化
陈拉斯24 分钟前
给公司年会写了个大屏抽奖系统:动画在前端跑,凭什么说结果没被改?
javascript
daols8826 分钟前
vue 甘特图组件 vxe-gantt 自动计算工期显示关键路径
vue.js·vxe-gantt
aa小小38 分钟前
Proxy 响应式原理
前端·proxy
计算机魔术师39 分钟前
Latent Space 访谈 TypeSafe CEO Diogo Almeida:Jev 是面向生产环境的 System One 模型而非万能 God 模型
前端
—Qeyser1 小时前
Element Plus 安装与配置指南 (Vue 3 + Vite + TS)
vue.js
雪芽蓝域zzs1 小时前
第19章:ECharts 组合图(折线 + 柱状混合图,双 Y 轴)
vue.js·echars
yzy851 小时前
Vue中下载或打开文件的JavaScript方法
前端·javascript·vue