vu3中的父子组件通讯

一、传统的props

通过在父组件中给子组件传值,然后在子组件中通过props接受数据

 1   //  父组件 
 2  < ValidateInput  3       type="text"
 4       v-model="emailVal"
 5       :rules='emailRules'
 6       placeholder='请输入邮箱地址'
 7       ref="inputRef"
 8  >
 9  </ValidateInput>
 10                      
 11   //  子组件 
 12  export  default  defineComponent({  13    name: 'ValidateInput' ,  14   props: {  15      rules: Array as PropType <RulesProp> ,  16   modelValue: String  17   },  18  }

二、通过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等事件函数移除了,emit()用于父子组件之间的沟通。

为了能够使用事务总线,除了emit触发函数还得有on监听函数。官方推荐使用第三方库mitt

因此事务总线的使用应该为

首先安装第三方库mitt

npm install --save mitt

然后在程序中使用事件总线

 1   //  父组件接受'form-item-created'频道 
 2  <script lang="ts">
 3  import { defineComponent, onUnmounted } from 'vue'
 4  import mitt from 'mitt'
 5  export const emitter = mitt()  6  export  default  defineComponent({  7    name: 'ValidateForm' ,  8   setup () {  9      const callback = (test: string) => {  10   console.log(test)  11   }  12      emitter.on('form-item-created' , callback)  13      onUnmounted(() => {  14        emitter.off('form-item-created' , callback)  15   })  16       return  {}  17   }  18   })  19  </script>
 20  
 21   //  子组件发送信息 
 22  onMounted(() => {  23   console.log(inputRef.val)  24        emitter.emit('form-item-created' , inputRef.val)  25  })

 

标签: Javascript

添加新评论