簡易版 vue實現

Vue-mini

完整的Demo示例:[email protected]:xsk-walter/Vue-mini.git
一、Vue實例

  1. 構造函數: $option\ $el\ $data 判斷是否存在 通過 || 邏輯運算符;
  2. _ProxyData 遍歷所有data屬性,並注入到vue實例中;
  3. 判斷是否重複選項;
// Vue.js
/**
 * 1.負責接收初始化的參數(選項)
 * 2.負責把data中的屬性注入到Vue實例,轉換成getter、setter
 * 3.負責調用observer監聽data中所有屬性的變化
 * 4.負責調用compiler解析指令、差值表達式
 */
/**
 * 類圖  類名 Vue
 * ---屬性
 * + $options
 * + $el
 * + $data
 * ---方法
 * - _ProxyData()
 */
class Vue {
    constructor(options) {
        // 1.通過屬性保存選項的數據
        this.$options = options || {}
        this.$data = options.data || {}
        this.$el = typeof this.$options.el === 'string' ? document.querySelector('#app') : this.$options.el
        
        // TODO:_ProxyData 和Observer的區別
        /**
         * _ProxyData: data中的屬性注入到vue實例
         * Observer: 把data中的屬性轉換為getter和setter
         */

        // 2.把data中的成員轉換成getter和setter,注入到vue實例中
        this._ProxyData(this.$data) 

        // 3.調用observer對象,監聽數據的變化
        new Observer(this.$data) 

        // 4.調用compiler對象,解析指令和差值表達式
        new Compiler(this)
    }

    _ProxyData(data) {
        // 遍歷所有的data屬性 轉化為 getter 和setter
        Object.keys(data).forEach(key => {
            // 把data中的屬性注入到vue實例中
            Object.defineProperty(this, key, {

                enumerable: true, // 可枚舉
                configurable: true, // 可配置

                get() {
                    return data[key]
                },

                set(newValue) {
                    if (data[key] === newValue) return
                    data[key] = newValue
                }
            })
        })
    }
}

二、Observer 數據劫持

1.data屬性數據劫持;

2.遞歸遍歷data屬性轉為getter、setter; Object.keys() => 獲取對象中的屬性;

3.數據變化發送通知;

4.避免get獲取數據時造成閉包;this.data[key]會觸發get方法,需要將值返回;

// Observer.js
/**
 * 1、將data選項中的屬性轉為getter和setter;
 * 2、data中的某個屬性也是對象,把該屬性轉換成響應式屬性;
 * 3、數據變化發布通知;
 */
/**
 * 類圖 類名 Observer
 * 方法
 * walk()
 * defineReactive()
 */
class Observer {

    constructor(data) {
        
        this.data = data
        this.walk(this.data)
    }

    walk(data) {

        // 1.判斷data是否是對象
        if (data && typeof data !== 'object') return

        // 2.遍歷data對象的所有屬性
        Object.keys(data).forEach(key => {
            this.defineReactive(data, key, data[key])
        })
    }

    
    defineReactive(data, key, val) {

        let that = this
        // 負責收集依賴,並發送通知
        let dep = new Dep()
        // 如果val是對象,把val內部的屬性轉換為響應式數據
        this.walk(val)

        Object.defineProperty(data, key, {
            enumerable: true,
            configurable: true,

            get() {
                // TODO:添加依賴 Dep.target(觀察者) = watcher對象;把watcher對象訂閱到Dep(目標對象)中去
                Dep.target && dep.addSub(Dep.target)

                return val // TODO:避免閉包; data[key]會觸發getter,所以返回val
            },

            set(newValue) {
                if (newValue === val) return
                val = newValue
                
                // 監聽修改後的數據,轉為getter、setter
                that.walk(newValue)

                // TODO:發送通知
                dep.notify()
            }
        })
  
    }

}

三、Compiler 編譯文本

1.操作節點:

  • Array.from 將偽數組轉為真數組

  • node節點(node.childNodes) 遍歷操作

  • 節點類型:node.nodeType = 3 文本節點、=1元素節點

  • 元素節點 獲取屬性 指令:node.attributes (偽數組) => Array.from(node.attributes) – attr.name / 屬性名稱

  • 處理文本節點:差值表達式 正則

    let reg = /\{\{(.+?)\}\}/  // 匹配差值表達式內容msg  {{msg}}
    let key = RegExp.$1.trim() // RegExp 正則構造函數
    
    node.textContent = node.textContent.replace(reg, this[key]) // replace 按照reg規則data替換 msg
    
// Compiler.js
/**
 * 1.負責編譯模板,解析指令、差值表達式;
 * 2.負責頁面首次渲染;
 * 3.當數據變化後重新渲染視圖;
 */

class Compiler {

    constructor(vm) {
        this.el = vm.$el
        this.vm = vm
        this.compile(this.el)
    }

    // 編譯模板,處理文本節點和元素節點
    compile(el) {
       let childNodes = el.childNodes

       if (childNodes && childNodes.length) {

           Array.from(childNodes).forEach(node => {

               if (this.isTextNode(node)) {

                   this.compileText(node)
               } else if (this.isElementNode(node)) {

                   this.compileElement(node)
               }

               //   node節點是否有子節點,如果有,遞歸調用compile 
               if (node.childNodes && node.childNodes.length) {
                   this.compile(node)
               }
           })
       }
        
    }

    // 編譯文本節點,處理差值表達式
    compileText(node) {
        let reg = /\{\{(.+?)\}\}/
        let content = node.textContent
        
        if (reg.test(content)) {
            let key = RegExp.$1.trim() // $1 為 reg中 匹配 ()中的文本內容
            node.textContent = node.textContent.replace(reg, this.vm[key])

            // 創建watcher對象,當數據改變更新視圖
            new Watcher(this.vm, key, (newValue) => {
                node.textContent = newValue
            })
        }
        
    }

    // 處理元素節點 、指令
    compileElement(node) {
        if (node.attributes && node.attributes.length) {
            // 遍歷所有的屬性節點
            Array.from(node.attributes).forEach(attr => {
                
                let attrName = attr.name.substr(2)
                // 判斷是否為指令
                if (this.isDirective(attr.name)) {

                    let key = attr.value

                    this.update(node, key, attrName)
                }

            })
        }
    }
 

    update(node, key, attrName) {

        let updateFn = this[attrName + 'Updater']
        updateFn && updateFn.call(this, node, this.vm[key], key)//TODO: call改變this指向 為 Compiler
        // this.textUpdater()
    }

    textUpdater(node, value, key) {
        
        node.textContent = value

        new Watcher(this.vm, key, newValue => {
            node.textContent = newValue
        })
    }

    modelUpdater(node, value, key) {
        node.value = value

        // 數據更新 - 更新視圖
        new Watcher(this.vm, key, newValue => {
            node.value = newValue
        })

        // TODO:雙向數據綁定 - 修改視圖 更新數據
        node.addEventListener('input', (val) => {

            this.vm[key] = val.target.value
        })
    }

    // 判斷為v-指令
    isDirective(attrName) {

        return attrName.startsWith('v-')
    }

    // 判斷文本節點
    isTextNode(node) {
        return node.nodeType === 3
    }

    // 判斷元素節點
    isElementNode(node) {
        return node.nodeType === 1
    }
}

四、Dep (dependency 依賴)

// Dep.js
/**
 * 1.收集依賴,添加觀察watcher;
 * 2.通知所有的觀察者;
 */

class Dep {

    constructor() {
        // 存儲所有的觀察者
        this.subs = []
    }

    // 添加觀察者
    addSub(sub) {
        if (sub && sub.update) {
            this.subs.push(sub)
        }
    }

    // 通知所有的觀察者
    notify() {
        this.subs.forEach(sub => {
            sub.update()
        })
    }
}

五、Watcher

1.自身實例化的時候往dep對象中添加自己;

2.當數據變化時觸發依賴,dep通知所有的Watcher實例更新視圖。

3.實例化時,傳入回調函數,處理相應操作。

// Watcher.js
/**
 * 1.數據變化觸發依賴,dep通知所有的Watcher實例更新視圖;
 * 2.自身實例化的時候往dep對象中添加自己;
 */

class Watcher {

    constructor(vm, key, cb) {
        this.vm = vm
        // data中的屬性名稱
        this.key = key
        // 回調函數負責更新視圖
        this.cb = cb

        // TODO:把watcher對象記錄到Dep類的靜態屬性target
        Dep.target = this
        // 觸發get方法,在get方法中會調用addSub方法
        this.oldValue = vm[key]
        Dep.target = null
    }

    // 當數據發生變化時更新視圖
    update() {
        let newValue = this.vm[this.key]

        if (newValue === this.oldValue) return
        // TODO: 回調
        this.cb(newValue)
    }
}
<!DOCTYPE html>
<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>
    <script src="./JS/Dep.js"></script>
    <script src="./JS/Watcher.js"></script>
    <script src="./JS/Compiler.js"></script>
    <script src="./JS/Observer.js"></script>
    <script src="./JS/Vue.js"></script>
</head>
<body>
    <div id="app">
        <div>差值表達式</div>
        <div>{{msg}}</div>
        <div>v-text</div>
        <div v-text="msg"></div>
        <div>v-model</div>
        <input v-model="msg" />
    </div>

    <script>

        let vm = new Vue({
            el: '#app',
            data: {
                msg: 'Hello World!',
                count: 0,
                obj: {
                    a: 'xsk'
                }
            },
            
        })

        console.log(vm, 'vm===')
    </script>
</body>
</html>

六、發布訂閱者模式、觀察者模式

Tags: