Vue3 子组件像父组件传递数据 自定义事件 defineEmits

介绍

很多情况下子组件都需要像父组件去传递一些数据,Vue3和Vue2传递值的写法不太一样。

例子

很常见的一个案例,弹出一个商品对话框,用户选择商品后把商品信息返回给父组件,使用自定义事件去做。
在这里插入图片描述

子组件

选择商品对话框

<template>
  <a-modal :open="open"
           title="选择商品"
           @cancel="close"
          :footer="false">
    <p>{{goods.name}}</p>
    <p>{{goods.pie}}</p>
    <p>{{goods.number}}</p>
    <a-button type="primary" @click="retGoods">选择商品</a-button>
  </a-modal>
</template>
<script setup>
import {reactive, ref ,defineEmits,defineProps } from "vue";

defineProps({
  open: {
    type: Boolean,
  },
})


const goods=reactive(({
  name:'鱼子酱',
  pie:9.9,
  number:100
}))

const emit=defineEmits(["select"])
//关键代码 select为触发父组件的事件

function retGoods(){
//goods为商品信息传递给父组件
  emit("select",goods)
}
</script>

在这里插入图片描述点击选择商品后将商品信息返回给父组件

父组件

点击选择商品后会触发@select事件

  <SelectDialog v-model:open="open" @select="selectGoods"></SelectDialog>

function  selectGoods(item) {
  console.log(item)
}

成功拿到数据
在这里插入图片描述

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-16 23:48:02       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-16 23:48:02       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-16 23:48:02       58 阅读
  4. Python语言-面向对象

    2024-07-16 23:48:02       69 阅读

热门阅读

  1. 开放开源开先河(一)

    2024-07-16 23:48:02       20 阅读
  2. 动态规划算法专题四--两个数组dp问题

    2024-07-16 23:48:02       19 阅读
  3. 如何检查对象中键是否存在?

    2024-07-16 23:48:02       22 阅读
  4. 【嵌入式】面试笔试问题整理 (持续更新)

    2024-07-16 23:48:02       22 阅读
  5. 微信小程序-组件通信

    2024-07-16 23:48:02       19 阅读