vue3组件通讯
DvorakChen 人气:0一、传统的props
通过在父组件中给子组件传值,然后在子组件中通过props接受数据
//父组件 <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等事件函数移除了,emit()用于父子组件之间的沟通。为了能够使用事务总线,除了emit触发函数还得有on监听函数。官方推荐使用第三方库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> //子组件发送信息 onMounted(() => { console.log(inputRef.val) emitter.emit('form-item-created', inputRef.val) })
加载全部内容