介绍

很多情况下子组件都需要像父组件去传递一些数据,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)
}

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

更多推荐