[Vue] MVVM model, data proxy

Model - View - ViewModel

Insert image description here

  • Model: datadata in
  • View:Template parsing-> DOMpage
  • ViewModel: Vueinstance object

vmThe content of can be Vueall the content of the prototype

data brokerObject.defineproperty(参数1, 参数2, 参数3)

  • Parameter 1: object
  • Parameter 2: attribute name
  • Parameter 3: Configuration item

Function example: defining variables

let number = 18
let person = {
    
    
	name = "zhangsan"
}

Function Example: Data Broker

Object.defineProperty(person, 'age', {
    
    
	get: function(){
    
    
		return number
	}
})

Data agent features:

  1. Not enumerable, cannot participate in traversal, solution: enumerableset the attribute to true, the default is false
  2. Unmodifiable, solution: writableset the attribute to true, the default is false
  3. Cannot be deleted, solution: configurableset the attribute to true, the default is false

Data proxy functions:

  1. Limit the data and see its characteristics
  2. getFunction: When the attribute of parameter 1 (object) is read, getthe function will be called, and the return value is the value of parameter 2 (attribute name). The Invoke Property gettermapping attribute getfunction is calledgetter

The setter can be understood in the same way:

When modifying parameter 2 (property name) of the object, the setter function will be called and the modified value will be received.

Object.defineProperty(person, 'age', {
    
    
	get: function(){
    
    
		return number
	}
	set(value){
    
    
		number = value
	}
})

Data proxy usage examples

let obj = {
    
    x:100}
let obj2 = {
    
    y:200}
Object.defineProperty(obj2, 'x', {
    
    
	get(){
    
    
		return obj.x
	}
	set(value){
    
    
		return obj.x = value
	}
})

Vuedata broker

  1. By vmreading name, inputting vm.name, calling getter, what is read is vm._data.nameinname
  2. By vmchanging name, changing vm.name, calling setter, what is changed is vm._data.nameinname
Verification vm._datais in the build parametersdata

vmStore datathe data in vm._data, vm._dataand the data hijacking cannot be directly verified. The data hijacking is to achieve responsiveness.

let data = {
    
    
	name = "zhangsan"
}
const vm = new Vue({
    
    
	el: '#root',
	data
})

Verifiablevm._data === data

VueData Broker Deep Understanding
  1. vmNo vm.name, only , but it can be accessed vm._datathrough the data agent via inputvm.namevm._data.name

  2. Without a data agent, the interpolation must be written as{ {_data.name}}

  3. vmGet it _data, add an attribute name, getterread _datait name, settermodify _dataitname

Guess you like

Origin blog.csdn.net/m0_50939789/article/details/128460915