Vue3之defineProps、defineEmits和defineExpose的使用及說明
更新時間:2025年10月11日 16:52:40 作者:樣子2018
文章介紹了Vue中defineProps、defineEmits和defineExpose的用途和作用,defineProps用于在子組件中定義類型安全的props,defineEmits允許子組件向父組件傳遞事件
一、使用說明
- defineProps 供了一種更加明確和類型安全的方式來定義子組件的 props,使得子父組件之間的數(shù)據(jù)傳遞更加清晰和可維護。
- defineEmits 實現(xiàn)子組件向父組件傳遞數(shù)據(jù)或事件。
- 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>總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
VUE UPLOAD 通過ACTION返回上傳結(jié)果操作
這篇文章主要介紹了VUE UPLOAD 通過ACTION返回上傳結(jié)果操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
Vue2.X和Vue3.0數(shù)據(jù)響應原理變化的區(qū)別
這篇文章主要介紹了Vue2.X和Vue3.0數(shù)據(jù)響應原理變化的區(qū)別,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-11-11

