vue雙向綁定與單向數(shù)據(jù)流

場景: 子組件是一個(gè)input或者textarea,父組件傳值到子組件用于回顯。

問題:最后提交數(shù)據(jù)的時(shí)候,沒有取到填寫的值。

問題原因: 由于vue父組件到子組件是“單向數(shù)據(jù)流”,但是input又使用了v-model雙向綁定數(shù)據(jù),在數(shù)據(jù)發(fā)生變化的時(shí)候,沒有通知父組件也改變對應(yīng)的數(shù)據(jù),就導(dǎo)致子組件維護(hù)的數(shù)據(jù)一直都是父組件流進(jìn)來的值,剛好傳進(jìn)來的是空,所以提交的時(shí)候就為空。

解決方法:子組件接收的的值用computed來進(jìn)行維護(hù) set方法中使用$emit('changeProps', newValue)通知父組件也更新傳進(jìn)來的值(我想在watch中應(yīng)該也可以解決,但是并沒有嘗試過)

貼上代碼:

// 子組件
<template>
  <input
    v-model="value"
    type="number"
    style="text-align:right;"
    onkeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"
    oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
  >
</template>

<script>
export default {
  props: {
    resultInfo: {
      type: String,
      default: '',
    }
  },
  computed: {
    value: {
      get() {
        if(this.resultInfo) {
          return this.resultInfo
        }
        return ''
      },
      set(newValue) {
        this.$emit('changeInputString', newValue)
      }
    }
  },
}
</script>
// 父組件
<template>
<input-string
  :result-info="trouble.resultInfo"
  @changeInputString="changeInputString($event, trouble)"
/>
</template>

<script>
export default {
  method: {
    changeInputString(e, trouble) {
      trouble.resultInfo = e
    },
  }
}
</script>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容