Vue3之defineProps、defineEmits和defineExpose的使用及说明
更新时间:2025年10月11日 16:52:40 作者:样子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>总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Vue3发送post请求出现400 Bad Request报错的解决办法
这篇文章主要给大家介绍了关于Vue3发送post请求出现400 Bad Request报错的解决办法,文中通过实例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下2023-02-02
Vue 解决父组件跳转子路由后当前导航active样式消失问题
这篇文章主要介绍了Vue 解决父组件跳转子路由后当前导航active样式消失问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-07-07
Vue中this.$router和this.$route的区别及push()方法
这篇文章主要给大家介绍了关于Vue中this.$router和this.$route的区别及push()方法的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2021-05-05


最新评论