Vue3 之defineProps、defineEmits和defineExpose说明
一、使用说明
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>

浙公网安备 33010602011771号