陈广安个人网站
会写代码的咸鱼
陈广安个人网站阿里云盘资源
陈广安个人网站网盘资源搜索
“ 梦想还是要有的,万一实现了呢!”
— 马云

vue3.2,组件中接收来自父组件的数据以及自定义事件

创建时间:2022-05-05

创建组件 sub.vue

<template>
  <div class="root">{{props.msg}}</div>
  <el-button @click="subForm">按钮</el-button>
</template>

<script setup>
  import { defineProps, defineEmits } from "vue"

  //自定义事件
  const emit = defineEmits(["ok"])

  //接受父组件参数
  const props = defineProps({
    msg: {
      type: String,
      default: ''
    },
    show: {
      type: Boolean,
      default: false
    },
    config: {
      type: Object,
      default: () => {
        return {}
      }
    },
  })

  //定义方法,触发自定义事件
  const subForm = () => {
    emit("ok", { data: '传给自定事件的默认参数' })
  }
</script>


页面中,使用组件

<template>
  <a-sub ref="sub" @ok="okEvent" msg="消息" show></a-sub>
</template>

<script setup>
  import aSub from "@/components/sub.vue";

  const okEvent = (data) => {
    //子组件 触发自定义事件 返回的数据
    console.log(data)
  };
</script>