美文网首页
vue双向绑定与单向数据流

vue双向绑定与单向数据流

作者: Vampire丶_L | 来源:发表于2020-06-19 10:49 被阅读0次

场景: 子组件是一个input或者textarea,父组件传值到子组件用于回显。

问题:最后提交数据的时候,没有取到填写的值。

问题原因: 由于vue父组件到子组件是“单向数据流”,但是input又使用了v-model双向绑定数据,在数据发生变化的时候,没有通知父组件也改变对应的数据,就导致子组件维护的数据一直都是父组件流进来的值,刚好传进来的是空,所以提交的时候就为空。

解决方法:子组件接收的的值用computed来进行维护 set方法中使用$emit('changeProps', newValue)通知父组件也更新传进来的值(我想在watch中应该也可以解决,但是并没有尝试过)

贴上代码:

// 子组件
<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>

相关文章

网友评论

      本文标题:vue双向绑定与单向数据流

      本文链接:https://www.haomeiwen.com/subject/qaxvxktx.html