第五十九:子传父 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>
相关推荐
内存不泄露6 分钟前
基于 Spring Boot 的医院预约挂号系统(全端协同)设计与实现
java·vue.js·spring boot·python·flask
森叶11 分钟前
Cookie 和 Token 的应用场景优势比较 & Cookie 不能使用的场景补充
javascript
IT_陈寒11 分钟前
SpringBoot 3.0实战:10个高效开发技巧让你的启动时间减少50%
前端·人工智能·后端
im_AMBER14 分钟前
前端 + agent 开发学习路线
前端·学习·agent
亿坊电商21 分钟前
利于SEO优化的CMS系统都有哪些特点?
前端·数据库
juejin_cn38 分钟前
使用 Codex SDK 轻松实现文字控制电脑
前端
CUYG38 分钟前
Moment.js常用
前端
用户812748281512039 分钟前
漏学Input知识系列之“偷”走了其他窗口的事件pilferPointers
前端
用户812748281512040 分钟前
安卓14自由窗口圆角处理之绘制圆角轮廓线
前端
用户812748281512040 分钟前
跨进程高级玩法方案2-学员分享
前端