Vue3子传父 组件传参 defineEmits

简介: Vue3子传父 组件传参 defineEmits

defineEmits 属性:用于创建自定义事件,接收子组件传递过来的数据。

注意:如果自定义事件的名称,和原生事件的名称一样,那么只会触发自定义事件。

defineEmits 仅适用于 setup 语法糖,其它写法请见:《Vue3 子传父 组件传参 emit》

// 子组件:创建自定义事件,传递数据
const emit = defineEmits(['自定义事件']);
emit('自定义事件', 数据1, 数据2);
 
// 父组件:绑定自定义事件,接收数据
<组件标签 @自定义事件="函数名"></组件标签>
 
const 函数名 = (参数1, 参数2) => {
  console.log(参数1, 参数2);
}

基础使用

一、子组件:创建自定义事件,传递数据。

<template>
  <h3>我是子组件</h3>
</template>
 
<script setup>
import { ref } from "vue";
let name = ref("张三");
// 创建 myEvent 自定义事件
const emit = defineEmits(['myEvent']);
// 使用 myEvent 自定义事件,传递数据
emit('myEvent', name.value, 999);
</script>

二、父组件:给组件标签绑定自定义事件,接收数据。

<template>
  <h3>我是父组件</h3>
  <p>{{ title }}</p>
  <hr />
  <!-- 绑定 myEvent 自定义事件 -->
  <Child @myEvent="add"></Child>
</template>
 
<script setup>
import Child from '../components/Child';
import { ref } from 'vue';
let title = ref();
// 创建事件函数,接收数据
const add = (name, num) => {
  title.value = name;
  console.log('我是父组件', name, num);
}
</script>

注:子组件使用自定义事件后,父组件中的事件函数会自动执行。

最终效果:


相关文章
|
3天前
|
JavaScript 数据库
ant design vue日期组件怎么清空 取消默认当天日期
ant design vue日期组件怎么清空 取消默认当天日期
|
3天前
|
JavaScript C++
vue高亮显示组件--转载
vue高亮显示组件--转载
8 0
|
2天前
|
JavaScript 前端开发 CDN
vue3速览
vue3速览
11 0
|
2天前
|
设计模式 JavaScript 前端开发
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
|
2天前
|
缓存 JavaScript 前端开发
Vue3 官方文档速通(中)
Vue3 官方文档速通(中)
9 0
|
2天前
|
缓存 JavaScript 前端开发
Vue3 官方文档速通(上)
Vue3 官方文档速通(上)
8 0
|
2天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
7 1
|
2天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
6 0
|
2天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
6 0
|
2天前
|
JavaScript 前端开发 API
Vue3 系列:从0开始学习vue3.0
Vue3 系列:从0开始学习vue3.0
8 1