欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue3中的父子組件通訊詳情

 更新時(shí)間:2022年06月07日 14:44:44   作者:DvorakChen  
這篇文章主要介紹了vue3中的父子組件通訊詳情,文章以傳統(tǒng)的props展開主題相關(guān)資料內(nèi)容,具有一定參考價(jià)值,需要的小伙伴可以參考一下

一、傳統(tǒng)的props

通過在父組件中給子組件傳值,然后在子組件中通過props接受數(shù)據(jù)

 //父組件
  <ValidateInput
       type="text"
       v-model="emailVal"
       :rules='emailRules'
       placeholder='請(qǐng)輸入郵箱地址'
       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='請(qǐng)輸入郵箱地址'
  ref="inputRef"
 >
</ValidateInput>

//實(shí)際上是
<ValidateInput
  type="text"
  :emailVal="emailVal"
  @update:modelValue="方法"
  placeholder='請(qǐng)輸入郵箱地址'
  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()用于父子組件之間的溝通。為了能夠使用事務(wù)總線,除了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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論