Understand vUE’s design philosophy

By abstracting the state and behavior of the View, let’s separate the View UI from the business logic.

The three elements of the MVVM framework are data responsiveness, the template engine and its rendering

  • Data responsive: Listens for data changes and updates in the view
  • Object.definePropetry()
  • Proxy
  • Template engine: Provides template syntax for describing views

Interpolation: {{}} instructions: V-bind, V-ON, V-model, V-for, V-if

  • Render: How do I convert templates to HTML

Template = > vdom = > dom

// Pass in the object obj and give it a property key, starting with val
// Future access to this property will be blocked, thus achieving responsiveness
function defineReactive(obj,key,val){
	// iterate down recursively
	observe(val) // Because the object's grandchild element cannot be obtained (set), the response does the processing of obj.a.b
    
    Object.defineProperty(obj,key,val,{
    	get(){
        	console.log("get",key)
            return val;
        },
        set()(newVal){
        	if(newVal ! == val){console.log("set", key); observe(newVal) val = newVal; }}}}// Automatically sets all properties of an object to reactive
function observe(obj){
	if(type obj ! = ="Object" || obj == null) {return obj;
    }
    Object.keys(obj).forEach((key) = >{ defineReactive(obj, key, obj[key]); })}const obj = {
  foo: "foo".bar: "bar".baz: { a: 1 },
  arr: [1.2.3]};// defineReactive(obj, 'foo', 'foo')
observe(obj);

Copy the code

application

<! DOCTYPEhtml>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>

<body>
    <div id="app"></div>
    <script>
        function defineReactive(obj, key, val) {
            Object.defineProperty(obj, key, {
                get() {
                    console.log('get', key);
                    return val
                },
                set(newVal) {
                    if(newVal ! == val) {console.log('set', key);
                        val = newVal
                        update()
                    }
                }
            })
        }
        const obj = {}
        defineReactive(obj, 'foo'.' ')

        function update() {
            app.innerText = obj.foo
        }
        setInterval(() = > {
            obj.foo = new Date().toLocaleTimeString()
        }, 1000)
    </script>
</body>

</html>
Copy the code