Vue中input框手动赋值成功却无法再编辑input框的值

2695

如下示例:

<a-form layout="vertical">
    <a-row :gutter="16">
        <a-col :span="24">
            <a-form-item label="名称">
                <a-input v-model="helloForm.name" placeholder="请输入名称"/>
            </a-form-item>
        </a-col>
    </a-row>
    <a-row :gutter="16">
        <a-col :span="24">
            <a-form-item label="描述">
                <a-input v-model="helloForm.description" placeholder="请输入描述"/>
            </a-form-item>
        </a-col>
    </a-row>
</a-form>
export default {
  name: 'helloFormDemo',
  data () {
    return {
      helloForm: {}
    }
  },
  methods: {
    handleEditHelloForm () {
        // 模拟编辑功能需要数据回显
        this.helloForm.name = 'hello 我是helloForm中的name值'
        this.helloForm.description = '我是一大段描述,此处省略很多字'
    }
  }
}

如此这样,表单虽然值回显的但是确实无法修改input框中的值的。

根据官方文档定义:如果在实例创建之后添加新的属性到实例上,它不会触发视图更新

由此Vue实例创建时,helloForm.属性名并未声明,因此Vue就无法对属性执行 getter/setter 转化过程,导致helloForm属性不是响应式的,因此无法触发视图更新。解决的方式有两种,第一种就是显示的声明helloForm这个对象的属性,如:

export default {
  name: 'helloFormDemo',
  data () {
    return {
      helloForm: {
          name: '',
          description: ''
      }
    }
  }
}

其次也可以使用使用Vue的全局API: $set()赋值:

export default {
  methods: {
    handleEditHelloForm () {
        // 模拟编辑功能需要数据回显
        this.$set(this.helloForm, 'name', '我是name')
      	this.$set(this.helloForm, 'description', '我是一大段描述,此处省略很多字')
    }
  }
}