0
Follow
0
View

vue __ob__Observer causes the assignment to fail

cvin456 注册会员
2023-02-28 17:24

This answer quotes ChatGPT

ob is an attribute used by Vue internally to implement Vue's responsive system. When an object is converted to a responsive object by Vue, Vue will add the ob attribute to the object. You also add getter and setter methods for the object's properties so that you can listen for property changes and trigger view updates.

The

assignment should be done after the object has been converted to a reactive object by Vue. If you print the object before the assignment, you will find that there is no ob property in the object, because the object has not been converted to a reactive object by Vue. So, before assigning, you need to convert the object to a reactive object by calling the $set or $watch method on the Vue instance. For example:

this.$set(this, 'a', JSON.parse(JSON.stringify(this.a)));

or:


this.$watch(() => this.a, (newValue) => {
  this.a = newValue;
}, { deep: true });

Doing so ensures that the assignment successfully modifies the properties of the object and triggers the view update.

patvice 注册会员
2023-02-28 17:24


In Vue.js, each reactive data is observed by an Observer inside Vue.js by adding an attribute called ob to the data. The observer listens for changes in the data and then notifies the components that depend on the data to rerender.

If you want to make a deep copy of reactive data and then reassign it to the same variable, the observer to which the variable was originally bound will be invalidated because it now points to a new data object. That's why you can't use the data externally.

If you do need to make a deep copy of reactive data, try merging the new data back into the original reactive data using the Vue.set() or this.$set() methods to preserve the reactive nature of the data

this.a = Object.assign({}, this.a, JSON.parse(JSON.stringify(this.a)));

Here the object.assign() method is used to merge the raw and deep-copy data into a new data Object, which is then reassigned using this.a. Since the merged data is still responsive, it does not invalidate the observer.

About the Author

Question Info

Publish Time
2023-02-28 17:24
Update Time
2023-02-28 17:24