JavaScript之實現一個簡單的Vue

vue的使用相信你們都很熟練了,使用起來簡單。可是大部分人不知道其內部的原理是怎麼樣的,今天咱們就來一塊兒實現一個簡單的vuehtml

Object.defineProperty()

實現以前咱們得先看一下Object.defineProperty的實現,由於vue主要是經過數據劫持來實現的,經過getset來完成數據的讀取和更新。vue

var obj = {name:'wclimb'}
var age = 24
Object.defineProperty(obj,'age',{
    enumerable: true, // 可枚舉
    configurable: false, // 不能再define
    get () {
        return age
    },
    set (newVal) {
        console.log('我改變了',age +' -> '+newVal);
        age = newVal
    }
})

> obj.age
> 24

> obj.age = 25;
> 我改變了 24 -> 25
> 25

從上面能夠看到經過get獲取數據,經過set監聽到數據變化執行相應操做,仍是不明白的話能夠去看看Object.defineProperty文檔。node

流程圖

html代碼結構

<div id="wrap">
    <p v-html="test"></p>
    <input type="text" v-model="form">
    <input type="text" v-model="form">
    <button @click="changeValue">改變值</button>
    {{form}}
</div>

js調用

new Vue({
        el: '#wrap',
        data:{
            form: '這是form的值',
            test: '<strong>我是粗體</strong>',
        },
        methods:{
            changeValue(){
                console.log(this.form)
                this.form = '值被我改變了,氣不氣?'
            }
        }
    })

Vue結構

class Vue{
        constructor(){}
        proxyData(){}
        observer(){}
        compile(){}
        compileText(){}
    }
    class Watcher{
        constructor(){}
        update(){}
    }
  • Vue constructor 構造函數主要是數據的初始化
  • proxyData 數據代理
  • observer 劫持監聽全部數據
  • compile 解析dom
  • compileText 解析dom裏處理純雙花括號的操做
  • Watcher 更新視圖操做

Vue constructor 初始化

class Vue{
        constructor(options = {}){
            this.$el = document.querySelector(options.el);
            let data = this.data = options.data; 
            // 代理data,使其能直接this.xxx的方式訪問data,正常的話須要this.data.xxx
            Object.keys(data).forEach((key)=> {
                this.proxyData(key);
            });
            this.methods = options.methods // 事件方法
            this.watcherTask = {}; // 須要監聽的任務列表
            this.observer(data); // 初始化劫持監聽全部數據
            this.compile(this.$el); // 解析dom
        }
    }

上面主要是初始化操做,針對傳過來的數據進行處理git

proxyData 代理data

class Vue{
        constructor(options = {}){
            ......
        }
        proxyData(key){
            let that = this;
            Object.defineProperty(that, key, {
                configurable: false,
                enumerable: true,
                get () {
                    return that.data[key];
                },
                set (newVal) {
                    that.data[key] = newVal;
                }
            });
        }
    }

上面主要是代理data到最上層,this.xxx的方式直接訪問datagithub

observer 劫持監聽

class Vue{
        constructor(options = {}){
            ......
        }
        proxyData(key){
            ......
        }
        observer(data){
            let that = this
            Object.keys(data).forEach(key=>{
                let value = data[key]
                this.watcherTask[key] = []
                Object.defineProperty(data,key,{
                    configurable: false,
                    enumerable: true,
                    get(){
                        return value
                    },
                    set(newValue){
                        if(newValue !== value){
                            value = newValue
                            that.watcherTask[key].forEach(task => {
                                task.update()
                            })
                        }
                    }
                })
            })
        }
    }

一樣是使用Object.defineProperty來監聽數據,初始化須要訂閱的數據。
把須要訂閱的數據到pushwatcherTask裏,等到時候須要更新的時候就能夠批量更新數據了。👇下面就是;
遍歷訂閱池,批量更新視圖。segmentfault

set(newValue){
        if(newValue !== value){
            value = newValue
            // 批量更新視圖
            that.watcherTask[key].forEach(task => {
                task.update()
            })
        }
    }

compile 解析dom

class Vue{
        constructor(options = {}){
            ......
        }
        proxyData(key){
            ......
        }
        observer(data){
            ......
        }
        compile(el){
            var nodes = el.childNodes;
            for (let i = 0; i < nodes.length; i++) {
                const node = nodes[i];
                if(node.nodeType === 3){
                    var text = node.textContent.trim();
                    if (!text) continue;
                    this.compileText(node,'textContent')                
                }else if(node.nodeType === 1){
                    if(node.childNodes.length > 0){
                        this.compile(node)
                    }
                    if(node.hasAttribute('v-model') && (node.tagName === 'INPUT' || node.tagName === 'TEXTAREA')){
                        node.addEventListener('input',(()=>{
                            let attrVal = node.getAttribute('v-model')
                            this.watcherTask[attrVal].push(new Watcher(node,this,attrVal,'value'))
                            node.removeAttribute('v-model')
                            return () => {
                                this.data[attrVal] = node.value
                            }
                        })())
                    }
                    if(node.hasAttribute('v-html')){
                        let attrVal = node.getAttribute('v-html');
                        this.watcherTask[attrVal].push(new Watcher(node,this,attrVal,'innerHTML'))
                        node.removeAttribute('v-html')
                    }
                    this.compileText(node,'innerHTML')
                    if(node.hasAttribute('@click')){
                        let attrVal = node.getAttribute('@click')
                        node.removeAttribute('@click')
                        node.addEventListener('click',e => {
                            this.methods[attrVal] && this.methods[attrVal].bind(this)()
                        })
                    }
                }
            }
        },
        compileText(node,type){
            let reg = /\{\{(.*?)\}\}/g, txt = node.textContent;
            if(reg.test(txt)){
                node.textContent = txt.replace(reg,(matched,value)=>{
                    let tpl = this.watcherTask[value] || []
                    tpl.push(new Watcher(node,this,value,type))
                    if(value.split('.').length > 1){
                        let v = null
                        value.split('.').forEach((val,i)=>{
                            v = !v ? this[val] : v[val]
                        })
                        return v
                    }else{
                        return this[value]
                    }
                })
            }
        }
    }

這裏代碼比較多,咱們拆分看你就會以爲很簡單了瀏覽器

  1. 首先咱們先遍歷el元素下面的全部子節點,node.nodeType === 3 的意思是當前元素是文本節點,node.nodeType === 1 的意思是當前元素是元素節點。由於可能有的是純文本的形式,如純雙花括號就是純文本的文本節點,而後經過判斷元素節點是否還存在子節點,若是有的話就遞歸調用compile方法。下面重頭戲來了,咱們拆開看:
if(node.hasAttribute('v-html')){
    let attrVal = node.getAttribute('v-html');
    this.watcherTask[attrVal].push(new Watcher(node,this,attrVal,'innerHTML'))
    node.removeAttribute('v-html')
}

上面這個首先判斷node節點上是否有v-html這種指令,若是存在的話,咱們就發佈訂閱,怎麼發佈訂閱呢?只須要把當前須要訂閱的數據pushwatcherTask裏面,而後到時候在設置值的時候就能夠批量更新了,實現雙向數據綁定,也就是下面的操做dom

that.watcherTask[key].forEach(task => {
    task.update()
})

而後push的值是一個Watcher的實例,首先他new的時候會先執行一次,執行的操做就是去把純雙花括號 -> 1,也就是說把咱們寫好的模板數據更新到模板視圖上。
最後把當前元素屬性剔除出去,咱們用Vue的時候也是看不到這種指令的,不剔除也不影響函數

至於Watcher是什麼,看下面就知道了this

Watcher

class Watcher{
    constructor(el,vm,value,type){
        this.el = el;
        this.vm = vm;
        this.value = value;
        this.type = type;
        this.update()
    }
    update(){
        this.el[this.type] = this.vm.data[this.value]
    }
}

以前發佈訂閱以後走了這裏面的操做,意思就是把當前元素如:node.innerHTML = '這是data裏面的值'、node.value = '這個是表單的數據'

那麼咱們爲何不直接去更新呢,還須要update作什麼,不是畫蛇添足嗎?
其實update記得嗎?咱們在訂閱池裏面須要批量更新,就是經過調用Watcher原型上的update方法。

效果

在線效果地址,你們能夠瀏覽器看一下效果,因爲本人太懶了,gif效果圖就先不放了,哈哈😄😄

完整代碼

完整代碼已經放到github上了 -> MyVue

參考

剖析Vue原理&實現雙向綁定MVVM
仿Vue實現極簡雙向綁定

相關文章
相關標籤/搜索