vue3中的父子組件通訊詳情
更新時間:2022年06月07日 14:44:44 作者:DvorakChen
這篇文章主要介紹了vue3中的父子組件通訊詳情,文章以傳統(tǒng)的props展開主題相關資料內容,具有一定參考價值,需要的小伙伴可以參考一下
一、傳統(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)
})到此這篇關于vu3中的父子組件通訊詳情的文章就介紹到這了,更多相關vu3組件通訊內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue+element搭建后臺小總結 el-dropdown下拉功能
這篇文章主要為大家詳細介紹了vue+element搭建后臺小總結,el-dropdown下拉功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-09-09
Vue中this.$router.push參數(shù)獲取方法
下面小編就為大家分享一篇Vue中this.$router.push參數(shù)獲取方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-02-02

