Home  >  Article  >  Web Front-end  >  How to implement one-way binding in the vue component passing object?

How to implement one-way binding in the vue component passing object?

亚连
亚连Original
2018-06-02 17:12:211771browse

Below I will share with you an example of implementing one-way binding in the object passed by the vue component. It has a good reference value and I hope it will be helpful to everyone.

When using vue components, data often needs to be passed between components. We will not discuss the situation of passing a string variable or numeric variable here. It is enough to read the official documentation. Here I propose that I will pass a string variable or a numeric variable between components. A pitfall encountered when passing objects.

When an object is passed between components, since the reference type of this object points to an address, if a certain attribute value of the object is modified in the child component, the corresponding attribute of the object in the parent component will also be modified accordingly. If there is a need for such two-way binding, then this is also a good method. However, if such two-way binding is not needed, then a new object must be defined to copy the properties and values ​​​​of the original object. The pitfall is here. If you use an ordinary var or let object, for example:

computed: { 
  data: function () { 
   let obj={}; 
   obj=this.message//this.message是父组件传递的对象 
   return obj 
 } 
 },

Bind each attribute in the data to the input box and try to modify it. You will find that the corresponding properties in the parent component The attribute value will still change, and the one-way binding effect is not achieved. At this time, a method needs to be added

computed: { 
 data: function () { 
  let obj=Object.assign({}, this.message); 
  return obj 
 } 
 },

The data returned in this way is a new object and will not point to the address of the original object. So modifying it will not affect the objects in the parent component.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

JS anonymous function and anonymous self-executing function concept and usage analysis

Solving the problem when installing as npm administrator Permission issues

vue-router related basic knowledge and working principles

The above is the detailed content of How to implement one-way binding in the vue component passing object?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn