Vue3之defineProps、defineEmits和defineExpose的使用及说明
作者:样子2018
文章介绍了Vue中defineProps、defineEmits和defineExpose的用途和作用,defineProps用于在子组件中定义类型安全的props,defineEmits允许子组件向父组件传递事件
一、使用说明
- defineProps 供了一种更加明确和类型安全的方式来定义子组件的 props,使得子父组件之间的数据传递更加清晰和可维护。
- defineEmits 实现子组件向父组件传递数据或事件。
- defineExpose 明确要暴露出去的属性和方法,使得父组件可以通过ref访问子组件的这些属性和方法,必须在变量和方法声明定义之后使用。
二、简单示例
- Test.vue
<template>
<div>
<p>{{msg}} - {{exposeStr}} - {{count}}</p>
<button @click="_click">set msg</button>
<button @click="count++">加</button>
<button @click="count--">减</button>
</div>
</template>
<script setup>
import {
ref
} from 'vue'
const exposeStr = ref('')
const count = ref(0)
const open = () => {
console.log('this is a open function')
}
const emit = defineEmits(['setMsg'])
const props = defineProps({
msg: {
type: String,
default: 'this is a test component'
}
})
const _click = () => {
emit('setMsg', {msg: props.msg})
}
defineExpose({
exposeStr,
open
})
</script>
<style>
</style>- App.vue
<script setup>
import Test from './components/Test.vue'
import {
ref
} from 'vue'
const detail = ref('')
const setMsg = (val) => {
detail.value.exposeStr = "set expose msg"
detail.value.open()
console.log(val)
}
</script>
<template>
<Test ref="detail" msg="this is a test component" @setMsg="setMsg"></Test>
</template>
<style>
</style>总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
