Vue3之defineProps、defineEmits和defineExpose的使用及說明
更新時間:2025年10月11日 16:52:40 作者:樣子2018
文章介紹了Vue中defineProps、defineEmits和defineExpose的用途和作用,defineProps用于在子組件中定義類型安全的props,defineEmits允許子組件向父組件傳遞事件
一、使用說明
- defineProps 供了一種更加明確和類型安全的方式來定義子組件的 props,使得子父組件之間的數(shù)據(jù)傳遞更加清晰和可維護(hù)。
- 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)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于json-bigint處理大數(shù)字問題
這篇文章主要介紹了關(guān)于json-bigint處理大數(shù)字問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05
Vue3發(fā)送post請求出現(xiàn)400?Bad?Request報錯的解決辦法
這篇文章主要給大家介紹了關(guān)于Vue3發(fā)送post請求出現(xiàn)400?Bad?Request報錯的解決辦法,文中通過實例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2023-02-02
詳解本地Vue項目請求本地Node.js服務(wù)器的配置方法
本文只針對自己需要本地模擬接口于是搭建一個本地node服務(wù)器供自己測試使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-03-03
Vue 解決父組件跳轉(zhuǎn)子路由后當(dāng)前導(dǎo)航active樣式消失問題
這篇文章主要介紹了Vue 解決父組件跳轉(zhuǎn)子路由后當(dāng)前導(dǎo)航active樣式消失問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07
Vue中this.$router和this.$route的區(qū)別及push()方法
這篇文章主要給大家介紹了關(guān)于Vue中this.$router和this.$route的區(qū)別及push()方法的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05

