首頁  >  文章  >  web前端  >  怎樣操作vue中.vue檔解析

怎樣操作vue中.vue檔解析

php中世界最好的语言
php中世界最好的语言原創
2018-06-02 11:18:251560瀏覽

這次帶給大家怎樣操作vue中.vue檔解析,操作vue中.vue檔解析的注意事項有哪些,下面就是實戰案例,一起來看一下。

vue 提供了一個compiler.parseComponent(file, [options]) 方法,來將.vue 檔案解析成一個descriptor:

// an object format describing a single-file component.
declare type SFCDescriptor = {
  template: ?SFCBlock;
  script: ?SFCBlock;
  styles: Array<SFCBlock>;
  customBlocks: Array<SFCBlock>;
};

##解析sfc 檔案的入口在src/sfc/parser.js 中,該檔案export 了parseComponent 方法, parseComponent 方法用來對單一檔案元件進行編譯。

接下來我們來看看 parseComponent 方法都做了哪些事情。

parseComponent 方法

function start(tag, attrs, unary, start, end,){
}
function end(tag, start, end){
}
parseHTML(content, {
  start,
  end
})
parseComponent 方法中定義了start``end 兩個

函數,之後呼叫了parseHTML 方法來對.vue 文件內容實踐編譯。

那麼這個 parseHTML 方法是做啥的呢?

parseHTML 方法

該方法看名字就知道是一個html-parser,可以簡單理解為,解析到每個起始標籤時,呼叫option 中的start;每個標籤結束時,呼叫option 中的end。

對應到這裡,就是分別呼叫 parseComponent 方法中定義的 start 和 end 函數。

在 parseComponent 中維護一個 depth 變量,在 start 中將 depth ,在 end 中 depth-- 。那麼,每個 depth === 0 的標籤就是我們需要獲取的信息,包含 template、script、style 以及一些自訂標籤。

start

每當遇到一個起始標籤時,執行 start 函數。

1、記錄下

current

Block。

每個 currentBlock 包含以下內容:

declare type SFCBlock = {
  type: string;
  content: string;
  start?: number;
  end?: number;
  lang?: string;
  src?: string;
  scoped?: boolean;
  module?: string | boolean;
};
2、根據 tag 名稱,將 currentBlock

物件在傳回結果物件中。

傳回結果物件定義為 sfc,如果tag不是 script,style,template 中的任一個,就放在 sfc.customBlocks 中。如果是style,就放在 sfc.styles 中。 script 和 template 則直接放在 sfc 下。

if (isSpecialTag(tag)) {
  checkAttrs(currentBlock, attrs)
  if (tag === 'style') {
    sfc.styles.push(currentBlock)
  } else {
    sfc[tag] = currentBlock
  }
} else { // custom blocks
  sfc.customBlocks.push(currentBlock)
}

end

每當遇到一個結束標籤時,執行 end 函數。

1、如果目前是第一層標籤(depth === 1),且 currentBlock 變數存在,那麼取出這部分text,放在 currentBlock.content 中。

if (depth === 1 && currentBlock) {
 currentBlock.end = start
 let text = deindent(content.slice(currentBlock.start, currentBlock.end))
 // pad content so that linters and pre-processors can output correct
 // line numbers in errors and warnings
 if (currentBlock.type !== 'template' && options.pad) {
  text = padContent(currentBlock, options.pad) + text
 }
 currentBlock.content = text
 currentBlock = null
}
2、depth-- 。

得到 descriptor
在將 .vue 整個遍歷一遍後,得到的 sfc 物件就是我們需要的結果。

產生 .js ?

compiler.parseComponent(file, [options]) 得到的只是一個元件的 SFCDescriptor ,最後編譯成.js 檔案是交給 vue-loader 等函式庫來做的。 ######相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章! ######推薦閱讀:#########如何使用react配合antd元件實作管理系統###############js圖片轉base64方法總結## #######

以上是怎樣操作vue中.vue檔解析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn