Sign in

Elementui form Object.assign Cannot edit after processing?

sviva edited in Tue, 24 Jan 2023
this.form = {};
Object.assign(this.form, this.tableData[index - 1]);//此时表单无法编辑
this.form= Object.assign({}, this.tableData[index - 1]);//这时可编辑
3 Replies
commented on Wed, 25 Jan 2023

Vue2 can't monitor the new attributes.

The above code is to set the form as an empty object, then listen to the empty object, and finally use assign to add attributes to the empty object, so that it cannot be listened to.

The following code is to declare an empty object, then add a property to the object, then assign the object to form, and finally the system listens to the object.

Vue precautions

commented on Wed, 25 Jan 2023

Excerpt from the official website:

Sometimes you may need to assign multiple new properties to an existing object, such as using Object.assign () or extend()。 However, the new property added to the object does not trigger the update. In this case, you should create a new object with the properties of the original object and the object to be mixed in.

// 代替 `Object.assign(this.someObject, { a: 1, b: 2 })`
this.someObject = Object.assign({}, this.someObject, { a: 1, b: 2 })

You can see the answer here on the official website: https://cn.vuejs.org/v2/guide/reactivity.html# Precautions for detecting changes

commented on Wed, 25 Jan 2023

Let's assume that's the case

data() {
  return {
    form: {}, // 此时form已经被改造,拥有响应式数据的功能

Let's assume that's the case

data() {
  return {
    form: {
        foo: 'foo', // 不仅form被改造,其中的foo也被改造

First of all, we need to know clearly when the data will be modified.

about Object.assign Imagine that tabledata is an object

const keys = Object.keys(this.tableData);
for (const key of keys) {
  this.form[key] = this.tableData[key]; // 这样写入的数据不会被改造

But if you write like this, the form is the data that has been modified. When you update it, the contents of the form will also be modified.

this.form = Object.assign(xxx);

So you can think about the following, in which test is not responsive

this.form.test = Object.assign(xxx);

How to check if there is no response? You can see if there is one__ OB object, or whether there is a reactivegetter / reactivesetter, the test in Figure 1 is not corresponding, because there is no__ ob

So how do you know these things better? I recommend that you can read some blog articles about Vue source code analysis, or try to read Vue source code yourself to know the above knowledge.