当前位置: 移动技术网 > IT编程>网页制作>Html5 > Vue.js 源码分析(二十) 指令篇 v-once指令详解

Vue.js 源码分析(二十) 指令篇 v-once指令详解

2019年07月08日  | 移动技术网IT编程  | 我要评论

数据绑定最常见的形式就是使用“mustache”语法 (双大括号) 的文本插值,例如:<p>message: {{ msg }}</p>以后每当msg属性发生了改变,插值处的内容都会自动更新。

可以给dom节点添加一个v-once指令,这样模板只会在第一次更新时显示数据,此后再次更新该dom里面引用的数据时,内容不会自动更新了,例如:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
    <div id="d" v-once>
        <p>{{message}}</p>
    </div>    
    <script>
        vue.config.productiontip=false;
        vue.config.devtools=false;
        var app = new vue({el:'#d',data:{message:'hello world!'}})
    </script>
</body>
</html>

dom渲染为:

为了验证修改message属性不会触发dom更新,我们在控制台输入app.message="hello vue"来修改message属性

可以发现dom并未更新,此时app.message等于"hello vue!"的,我们打印看看,如下:

可以看到app.message等于hello vue!,为什么没有触发更新了,因为vue内部把模板缓存起来了,把v-once对应的节点当作一个静态节点来看待,而不是一个响应式的数据(没有经过object.defineproperty处理)


 源码分析


 在解析模板生成ast节点树对象的时候会通过processonce尝试去获取v-once指令,如果有定义则在当前ast对象上增加一个once属性,值为true,如下:

function processonce (el) {     //第9460行 解析v-once属性    
  var once$$1 = getandremoveattr(el, 'v-once');     //获取v-once属性
  if (once$$1 != null) {                            //如果存在,则给el增加一个once属性,值为true
    el.once = true;
  }
}

例子里的模板解析时执行到这里后等于:

 

接下来在generate生成rendre函数的时候会先判断ast中有无once属性,如果有则调用genonce函数,genonce会调用genstatic()去生成一个静态节点

function genelement (el, state) {           //第10139行  生成函数字符串
  if (el.staticroot && !el.staticprocessed) {
    return genstatic(el, state)   
  } else if (el.once && !el.onceprocessed) {    //如果有设置了once属性,则调用genonce()函数
    return genonce(el, state)
  } else if (el.for && !el.forprocessed) {
  /*略*/
}

function genonce (el, state) {              //第10179行  渲染v-once指令
  el.onceprocessed = true;
  if (el.if && !el.ifprocessed) {             //如果有定义了v-if指令
    return genif(el, state)
  } else if (el.staticinfor) {                //如果是在v-for环境下
    var key = '';
    var parent = el.parent;
    while (parent) {
      if (parent.for) {
        key = parent.key;
        break
      }
      parent = parent.parent;
    }
    if (!key) {
      "development" !== 'production' && state.warn(
        "v-once can only be used inside v-for that is keyed. "
      );
      return genelement(el, state)
    }
    return ("_o(" + (genelement(el, state)) + "," + (state.onceid++) + "," + key + ")")
  } else {
    return genstatic(el, state)               //否则直接调用genstatic()函数
  }
}

genstatic函数是静态节点渲染时的分支,如下:

function genstatic (el, state) {      //第10172行 
  el.staticprocessed = true;
  state.staticrenderfns.push(("with(this){return " + (genelement(el, state)) + "}"));           //再次调用genelement(el, state),但是结果保存到state.staticrenderfns里面
  return ("_m(" + (state.staticrenderfns.length - 1) + (el.staticinfor ? ',true' : '') + ")")   //对于静态节点,返回格式为_m(id),id为staticrenderfns数组属性里的索引,生成vnode时用于缓存用的
}

对于v-once和静态节点来说,渲染后它的render函数是一个_m函数,其中参数是一个索引值,是存储在staticrenderfns数组属性对应的索引,每个值是一个静态dom,只会渲染一次的

例子里的模板渲染后等于render和staticrenderfns属性如下:

最后执行render函数的时候就会执行_m(0)这个函数,_m等于全局的renderstatic函数,如下:

function renderstatic (       //第3869行 渲染静态节点
  index,
  isinfor
) {
  var cached = this._statictrees || (this._statictrees = []);         //这个是缓存
  var tree = cached[index];                                           //尝试从缓存中拿到tree
  // if has already-rendered static tree and not inside v-for,
  // we can reuse the same tree.
  if (tree && !isinfor) {                                             //如果该静态ast在缓存中有了,而且不是在v-for环境下
    return tree                                                         //则直接返回tree即可
  }   
  // otherwise, render a fresh tree.
  tree = cached[index] = this.$options.staticrenderfns[index].call(   //调用$options.staticrenderfns里对应的函数渲染成一个vnode,并保存到缓存中
    this._renderproxy,
    null,
    this // for render fns generated for functional component templates
  );      
  markstatic(tree, ("__static__" + index), false);                    //设置标记
  return tree
}

可以看到对于v-once节点来说,如果没有和v-if或v-for配合使用,则它会被当作一个静态节点来对待,经过了第一次渲染后就会把模板缓存起来,以后的更新渲染都只是从缓存中拿出结果而已。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网