当前位置: 首页 > news >正文

Vue3的definePros和defineEmits

在 Vue 3 中,definePropsdefineEmits 是组合式 API 中用于定义组件的 props事件 的方法,提供了一种更简洁和明确的方式来管理组件的输入和输出。它们属于 Composition API 的一部分,在 Vue 2 中通常使用 props$emit 来实现。

1. defineProps

defineProps 用来定义组件的 props,即组件从父组件接收的属性。它使得在 <script setup> 中使用 props 变得更加简单和类型安全。

基本用法:
<script setup>
import { defineProps } from 'vue';// 定义 props
const props = defineProps({msg: {type: String,required: true},count: {type: Number,default: 0}
});
</script><template><div><p>{{ props.msg }}</p><p>{{ props.count }}</p></div>
</template>
解释:
  • defineProps 接收一个对象,可以为每个 prop 提供类型、默认值、是否必填等信息。
  • 在 <template> 中直接访问 props,无需手动定义 props
类型推导:

如果使用 TypeScript,可以通过类型推导让 props 更加明确和安全:

<script setup lang="ts">
import { defineProps } from 'vue';interface Props {msg: string;count: number;
}const props = defineProps<Props>();
</script>

2. defineEmits

defineEmits 用于定义组件触发的 自定义事件。它让你在 <script setup> 中声明组件发出的事件,并确保事件名称的类型安全。

基本用法:
<script setup>
import { defineEmits } from 'vue';// 定义事件
const emit = defineEmits<{(event: 'update', newValue: string): void;
}>();// 触发事件
const changeValue = () => {emit('update', 'new value');
};
</script><template><button @click="changeValue">Change Value</button>
</template>
解释:
  • defineEmits 接受一个对象或类型,它定义了所有可能触发的事件及其参数类型。
  • emit 是一个函数,用于触发自定义事件,在 Vue 3 中无需手动绑定 $emit
多事件支持:

你也可以定义多个事件:

<script setup>
const emit = defineEmits<{(event: 'update', newValue: string): void;(event: 'delete', id: number): void;
}>();
</script>

3. 组合使用

你可以在一个组件中同时使用 definePropsdefineEmits,以便管理组件的输入和输出。

<script setup>
import { defineProps, defineEmits } from 'vue';// 定义 props
const props = defineProps({title: String
});// 定义事件
const emit = defineEmits<{(event: 'updateTitle', newTitle: string): void;
}>();// 触发事件
const updateTitle = () => {emit('updateTitle', 'New Title');
};
</script><template><h1>{{ props.title }}</h1><button @click="updateTitle">Update Title</button>
</template>

总结:

  • defineProps:用于定义组件的输入(即 props),提供了类型推导和默认值的支持。
  • defineEmits:用于定义组件的输出(即触发的事件),提供了事件类型安全。

这两个方法大大简化了组件的编写,使得代码更加简洁、可维护,并且提供了更强的类型安全。如果你用 TypeScript,它们能帮助你避免很多常见的错误。

http://www.dtcms.com/a/288436.html

相关文章:

  • Nacos:微服务架构的核心引擎
  • xss-dom漏洞
  • Python 数据分析模板在工程实践中的问题诊断与系统性解决方案
  • 2025在线教育系统源码、平台开发新趋势:开源架构+AI赋能
  • FPGA自学——整体设计思路
  • MySQL练习3
  • 轻松上手:从零开始启动第一个 Solana 测试节点
  • 小架构step系列19:请求和响应
  • Redis字符串操作指南:从入门到实战应用
  • 81、【OS】【Nuttx】【启动】caller-saved 和 callee-saved 示例:压栈内容
  • MC0462最后一难
  • Redis进阶--集群
  • C study notes[1]
  • LVS技术知识详解(知识点+相关实验部署)
  • simulink系列之模型接口表生成及自动连线脚本
  • 消息队列:数字化通信的高效纽带
  • SQL Server和PostgreSQL填充因子
  • HCIA综合实验
  • string【下】- 内功修炼(搓底层)
  • C++入门--lesson4
  • CCF编程能力等级认证GESP—C++6级—20250628
  • ICT测试原理之--什么是假短
  • 基于opencv的人脸识别考勤系统
  • 人工智能与心理史学:从阿西莫夫的科幻预言到可计算社会模型>
  • Chris Fraser | 中国早期思想中墨家与荀子的知识论
  • 【完整代码】融合时序轨迹与49维特征反演的双色球开奖预测模型:一项关于隐藏规律的探索
  • Maven常用知识总结
  • Docker容器原理和启动策略
  • 传统浏览器过时了?Dia如何用AI重新定义上网体验
  • 零基础学习性能测试第二章-linux服务器监控:内存监控