current position:Home>Data broker in Vue

Data broker in Vue

2021-08-27 00:14:58 badspider

This is my participation 8 The fourth of the yuegengwen challenge 22 God , Check out the activity details :8 Yuegengwen challenge

1. What is a data broker

Data brokers : The operation of properties in another object through an object proxy ( read / Write )

When you put an ordinary JavaScript Object to Vue Instance as  data  Options ,Vue All of the objects will be traversed property, And use  Object.defineProperty  Put these property All converted to  getter/setter.

For example, you define an object a And an object b, You can use it. b Modify the properties inside a The properties inside , This is responsive , So how did this happen

2. principle

Object.defineProperty() Method defines a new property directly on an object , Or modify the existing properties of an object , And return this object .

Object.defineProperty(obj, prop, descriptor)
 Copy code 
  • among obj Is the object you want to define properties
  • prop Is the attribute you want to define
  • desciptor Is the property descriptor to define or modify

Attributes added by this method cannot be enumerated by default

If you want the properties to be enumerated , You can use the following configuration

    Object.defineProperty(a,'name',{
        value:'badspider',
        enumerable: true
    })
 Copy code 

that vue The data broker in is based on this method getter and setter

these getter/setter Invisible to users , But inside they let Vue Be able to track dependencies , stay property Notification of changes when accessed and modified

    let a = {
        name:"badspider"
    }

    let b = {}

    object.defineProperty(b,'name',{
            get(){
                    console.log(' I was called ')
                    return  a.name
        }
            set(value){
                    console.log(' I've been modified ')
                    return a.name = value
            }
    })
 Copy code 

When you need to read the data in this ,get function (getter) It will be called , Give you the data , When you modify data ,set function (setter) Will be called to modify data The value in

image.png In this way, you can be a data agent , Of course, this is just a very simple demonstration

copyright notice
author[badspider],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827001455620r.html

Random recommended