vue模板解析原理

<!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>
</head>
<body>

    <div id="app">
        <h1> {
   
   { name }} </h1>
        {
   
   {name}}
    </div>

    <script>
        const app = new Vue({
      
      
            el: '#app',
            data: {
      
      
                name: '温情key'
            }
        })
    </script>
</body>
</html>

解析前页面显示

在这里插入图片描述

vue是如何解析成我们定义data所对应的值

class Vue {
    
    
    constructor(options) {
    
    
        this.$el = document.querySelector(options.el);
        this.$data = options.data;
        this.compile(this.$el);
    };

    compile(node) {
    
    
        // node.childNodes 节点的所有子节点
        node.childNodes.forEach((item, index) => {
    
    
            // nodeType 节点类型  1代表元素节点 3代表文本节点  如果文本节点有{
    
    {}}就替换成数据
            if(item.nodeType === 1) {
    
      // <h1> {
    
    { name }} </h1>
                if(item.childNodes.length > 0) {
    
    
                    this.compile(item);
                }
            }
            if(item.nodeType === 3) {
    
      // {
    
    {name}}
                // 正则匹配{
    
    {}}
                let reg = /\{\{(.*?)\}\}/g;
                let text = item.textContent;  // textContent  节点内容
                // 给节点赋值
                item.textContent = text.replace(reg, (match, vmKey) => {
    
    
                    vmKey = vmKey.trim();
                    return this.$data[vmKey];
                })
            }
        })
    };
}

解析后页面显示

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_48960335/article/details/123957848