Vue3的definePros和defineEmits
在 Vue 3 中,defineProps
和 defineEmits
是组合式 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. 组合使用
你可以在一个组件中同时使用 defineProps
和 defineEmits
,以便管理组件的输入和输出。
<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,它们能帮助你避免很多常见的错误。