vue双向绑定原理分析(一)—模板解析编译

技术 · 2023-07-19
vue双向绑定原理分析(一)—模板解析编译

vue底层是如何实现模板解析的呢?
在html中写这样的代码:

    <div id="app">
        {{str}}
        <h1>{{str}}</h1>
        <ul>
            <li>{{text}}</li>
        </ul>
    </div>

js中:

new Vue({
    el:'#app',
    data:{
        str:'你好,哈哈中国',
        text:'好的'
    }
})

引入vue.js:

class Vue{
    constructor(options) {
        this.$el = document.querySelector(options.el) //获取el元素
        this.$data=options.data
        this.compile(this.$el) 
    }
    compile(node) {
        //对节点进行循环遍历
        node.childNodes.forEach((item) => {
            /**
             * nodeType:可以获取到节点的类型,可以通过数字判断你这个节点到底是哪种类型的节点
             * 元素节点:1
             * 属性节点:2
             * 文本节点:3
             * 注释节点:8
             */
            if (item.nodeType === 1) { 
                if (item.childNodes.length > 0) {
                    this.compile(item)
                }
            }
            
            if (item.nodeType === 3) {
                let reg = /\{\{(.*?)\}\}/g;//正则替换{{}}
                let text = item.textContent;
                item.textContent = text.replace(reg, (match,vmKey) => {
                    vmKey =vmKey.trim()
                    return this.$data[vmKey]
                })
            }
        })
    }
}
vue
Theme Jasmine by Kent Liao