Vue.js 源碼分析(二十一) 指令篇 v-pre指令詳解

該指令會跳過所在元素和它的子元素的編譯過程,也就是把這個節點及其子節點看成一個靜態節點來處理,例如:html

<!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="app">
        <p v-pre :title="message">{{message}}</p>  
        <p>{{message}}</p>
    </div>
    <script>
        Vue.config.productionTip=false;
        Vue.config.devtools=false;
        var app = new Vue({
            el:'#app',
            data:{message:"Hello World"}
        })
    </script>
</body>
</html>

編譯後的結果爲:vue

對應的HTML節點樹爲:node

能夠看到:title屬性也被當成了特性來處理了,咱們在控制檯輸入app.message="Hello Vue!"看看渲染變化:npm

能夠看到對於v-pre對應的DOM節點,數據變化時也不會觸發渲染的app

 

源碼分析函數


 解析模板時若是遇到標籤開始,會執行start函數,對於 <p v-pre :title="message">{{message}}</p>來講源碼分析

start: function start (tag, attrs, unary) {   //第9136行  解析到標籤開始時執行到這裏
      /**/

      if (!inVPre) {                            //若是inVPre爲false  inVPre是個全局,用於判斷當前是否在v-pre屬性的環境之下,好比<p v-pre><span>123</span></p>解析到span標籤時能夠經過該屬性來判斷當前在v-pre內
        processPre(element);                      //嘗試解析v-pre屬性
        if (element.pre) {                        //若是element有v-pre屬性
          inVPre = true;                            //則設置inVPre爲true
        }
      }
      if (platformIsPreTag(element.tag)) {
        inPre = true;
      }
      if (inVPre) {                             //若是當前爲pre標籤  
        processRawAttrs(element);                  //則設置inPre爲true
      } else if (!element.processed) {          
        // structural directives
        processFor(element);                      //對於v-pre特性標記的節點來講,不會進行這裏面的分支,也就不會處理Vue指令了
        processIf(element);
        processOnce(element);
        // element-scope stuff
        processElement(element, options);
      }

      /**/
    },

processRawAttrs用於將特性保存到AST對象的attrs屬性上,以下:this

function processRawAttrs (el) {     //第9317行 若是設置了v-pre特性,則執行到這裏
  var l = el.attrsList.length; 
  if (l) {
    var attrs = el.attrs = new Array(l); 
    for (var i = 0; i < l; i++) {         //遍歷當前全部的特性,依次保存到e.attrs上面
      attrs[i] = {
        name: el.attrsList[i].name,
        value: JSON.stringify(el.attrsList[i].value)
      };
    }
  } else if (!el.pre) {
    // non root node in pre blocks with no attributes
    el.plain = true;
  }
}

後面在gendata()函數執行時就會拼湊成attr屬性裏,最後render渲染成相應的DOM節點後就會將該attr屬性保存到對應的節點上了,例子裏的模板渲染成render函數以下:spa

with(this){return _c('div',{attrs:{"id":"app"}},[_c('p',{pre:true,attrs:{":title":"message"}},[_v("{{message}}")]),_v(" "),_c('p',[_v(_s(message))])])}

紅色標記的就是v-pre編譯後的模板,等到p元素渲染成真實DOM節點的時候,就會觸發Vue內部attrs模塊的updateAttrs方法進行初始化,以後就和v-bind指令裏的後部分流程時同樣的,最後會調用原生的DOM函數setAttribute去設置特性.net

相關文章
相關標籤/搜索