导航


HTML

CSS

JavaScript

浏览器 & 网络

版本管理

框架

构建工具

TypeScript

性能优化

软实力

算法

UI、组件库

Node

业务技能

针对性攻坚

AI


模板语法

Untitled

插值表达式

<h1 class="title">{{ title }}</h1>

{{ title }} -> 是插值表达式

mustache

地址

https://github.com/janl/mustache.js

安装

npm install mustache --save

使用

import Mustache from 'mustache';

var data = {
  title: 'This is my TITLE for MUSTACHE'
};

var html = Mustache.render(
  '<h1 class="title">{{ title }}</h1>',
  data
);

document.getElementById('app').innerHTML = html;

Vue 的模板语法

template 写法

const App = {
  data() {
    return {
      title: 'This is my TITLE for MUSTACHE',
      author: 'Lance',
      dateTime: new Date(),
      content: 'This is my CONTENT',
    }
  },
  template: `
    <div>
      <h1 class="title">{{ title }}</h1>
      <p>
        <span class="author">{{ author }}</span> - {{ dateTime }}
      </p>
      <p v-bind:title="content">{{ content }}</p>
    </div>
  `
}

Vue.createApp(App).mount('#app');

h 函数写法

import { h } from 'vue';

const App = {
  data() {
    return {
      title: 'This is my TITLE for MUSTACHE',
      author: 'Lance',
      dateTime: new Date(),
      content: 'This is my CONTENT',
    }
  },
  // template: `
  //   <div>
  //     <h1 class="title">{{ title }}</h1>
  //     <p>
  //       <span class="author">{{ author }}</span> - {{ dateTime }}
  //     </p>
  //     <p v-bind:title="content">{{ content }}</p>
  //   </div>
  // `,
  render() {
    // h函数参数:
    // 1. 目标标签,2. 属性集合 3. 子元素
    return h(
      'div',
      {},
      [
        h(
          'h1',
          {
            class: 'title'
          },
          this.title
        ),
        h(
          'p',
          {},
          [
            h(
              'span',
              {
                class: 'author',
              },
              this.author
            ),
            ` - ${this.dateTime}`
          ]
        ),
        h(
          'p',
          {
            title: this.title
          },
          this.content
        )
      ]
    )
  }
}

Vue.createApp(App).mount('#app');

template 到真实节点

1. render 函数编译 template 模板

render 函数获取 template(直接写 template,或者显示声明 render 函数)

Untitled

Untitled

2. template 转 AST(抽象语法树)

目的:解析那些 template 中不符合 html 原生的属性、指令、双大括号等

ast树的样子:

逻辑:识别一段 html 就删除一段,直到最后整个字符串被删除完,最终形成一个完整的AST树

e.g. function fn(a, b) {} 被解析成了下边对象样子

Untitled

Untitled

3. AST 树 转 虚拟 DOM

例如一个div元素被解析成下面的虚拟节点

Untitled

其中:

  1. _c 生成元素虚拟节点
  2. _v 生成文本虚拟节点
  3. _s 解析双大括号

Untitled

4. 虚拟 DOM 打 patch 补丁最终生成真实 DOM

整个过程:

  1. template 转 AST 树(分析 html 字符串,解析表达式/自定义属性/指令...)
  2. AST树 转 虚拟DOM
  3. 虚拟DOM 打 patch 补丁
  4. 生成真实DOM
  5. 最终走 render 函数更新

Untitled