vue循环生成元素_手写Vue源码(二) - 文本编译

模板编译

源码地址:传送门

在数据劫持中,我们完成了Vuedata选项中数据的初始操作。这之后需要将html字符串编译为render函数,其核心逻辑如下:

render函数的情况下会直接使用传入的render函数,而在没有render函数的情况下,需要将template编译为render函数。其具体逻辑如下:

  1. 获取template字符串
  2. template字符串解析为ast抽象语法树
  3. ast抽象语法树生成代码字符串
  4. 将字符串处理为render函数赋值给vm.$options.render

获取template字符串

在进行template解析之前,会进行一系列的条件处理,得到最终的template,其处理逻辑如下:

5cd2e544c9644607774bbf1544a0b974.png

src/init.js中书写如下代码:

/**
 * 将字符串处理为dom元素
 * @param el
 * @returns {Element|*}
 */
function query (el) {
    
  if (typeof el === 'string') {
    
    return document.querySelector(el);
  }
  return el;
}

function initMixin (Vue) {
    
  Vue.prototype._init = function (options) {
    
    const vm = this;
    vm.$options = options;
    initState(vm);
    const {
     el } = options;
    // el选项存在,会将el通过vm.$mount方法进行挂载
    // el选项如果不存在,需要手动调用vm.$mount方法来进行组件的挂载
    if (el) {
    
      vm.$mount(el);
    }
  };
  Vue.prototype.$mount = function (el) {
    
    el = query(el);
    const vm = this;
    const options = vm.$options;
    if (!options.render) {
     // 有render函数,优先处理render函数
      let template = options.template;
      // 没有template,使用el.outerHTML作为template
      if (!template && el) {
    
        template = el.outerHTML;
      }
      options.render = compileToFunctions(template);
    }
  };
}

当我们得到最终的template后,需要调用compileToFunctionstemplate转换为render函数。在compileToFunctions中就是模板编译的主要逻辑。

创建src/compiler/index.js文件,其代码如下:

export function compileToFunctions (template) {
    
  // 将html解析为ast语法树
  const ast = parseHtml(template);
  // 通过ast语法树生成代码字符串
  const code = generate(ast);
  // 将字符串转换为函数
  return new Function(`with(this){return ${
    code}}`);
}

解析html

当拿到对应的html字符串后,需要通过正则来将其解析为ast抽象语法树。简单来说就是将html处理为一个树形结构,可以很好的表示每个节点的父子关系。

下面是一段html,以及表示它的ast:

<body>
<div id="app">
  hh
  <div id="aa" style="font-size: 18px;">hello {
    {name}} world</div>
</div>
<script>
  const vm = new Vue({
    
    el: '#app',
    data () {
    
      return {
    
        name: 'zs',
      };
    },
  });
</script>
</body>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值