vue3中的父子組件通訊詳情
一、傳統(tǒng)的props
通過在父組件中給子組件傳值,然后在子組件中通過props接受數(shù)據(jù)
//父組件 <ValidateInput type="text" v-model="emailVal" :rules='emailRules' placeholder='請輸入郵箱地址' ref="inputRef" > </ValidateInput> //子組件 export default defineComponent({ name: 'ValidateInput', props: { rules: Array as PropType <RulesProp>, modelValue: String }, }
二、通過modeValue綁定
//v-model簡寫 <ValidateInput type="text" v-model="emailVal" placeholder='請輸入郵箱地址' ref="inputRef" > </ValidateInput> //實際上是 <ValidateInput type="text" :emailVal="emailVal" @update:modelValue="方法" placeholder='請輸入郵箱地址' ref="inputRef" > </ValidateInput> //子組件 <template> <div class="inputItem"> <input type="text" :value="inputRef.val" @input="updateValue" id="emial" > </div> </template> export default defineComponent({ name: 'ValidateInput', props: { rules: Array as PropType <RulesProp>, modelValue: String }, setup (props, context) { const inputRef = reactive({ val: props.modelValue || '', isError: false, message: '' }) const updateValue = (e:KeyboardEvent) => { const targetValue = (e.target as HTMLInputElement).value inputRef.val = targetValue context.emit('update:modelValue', targetValue) } return { inputRef, updateValue } }
三、事件廣播(vue3中$on和$emit已廢棄),使用新的插件mitt
Vue3.0版本中把on,off、onece等事件函數(shù)移除了,emit()用于父子組件之間的溝通。為了能夠使用事務總線,除了emit觸發(fā)函數(shù)還得有on監(jiān)聽函數(shù)。官方推薦使用第三方庫mitt
首先安裝第三方庫mitt
npm install --save mitt
然后在程序中使用事件總線:
//父組件接受'form-item-created'頻道 <script lang="ts"> import { defineComponent, onUnmounted } from 'vue' import mitt from 'mitt' export const emitter = mitt() export default defineComponent({ name: 'ValidateForm', setup () { const callback = (test: string) => { console.log(test) } emitter.on('form-item-created', callback) onUnmounted(() => { emitter.off('form-item-created', callback) }) return {} } }) </script> //子組件發(fā)送信息 onMounted(() => { console.log(inputRef.val) emitter.emit('form-item-created', inputRef.val) })
到此這篇關(guān)于vu3中的父子組件通訊詳情的文章就介紹到這了,更多相關(guān)vu3組件通訊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue 如何將二維數(shù)組轉(zhuǎn)化為一維數(shù)組
這篇文章主要介紹了vue 如何將二維數(shù)組轉(zhuǎn)化為一維數(shù)組,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04Vue3結(jié)合TypeScript項目開發(fā)實踐總結(jié)
本文主要介紹了Vue3結(jié)合TypeScript項目開發(fā)實踐總結(jié),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09公共Hooks封裝文件下載useDownloadFile實例詳解
這篇文章主要為大家介紹了公共Hooks封裝文件下載useDownloadFile實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11Vue 使用beforeEach實現(xiàn)登錄狀態(tài)檢查功能
今天小編就為大家分享一篇Vue 使用beforeEach實現(xiàn)登錄狀態(tài)檢查功能,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10vue element-ui el-table組件自定義合計(summary-method)的坑
這篇文章主要介紹了vue element-ui el-table組件自定義合計(summary-method)的坑及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02