首頁 > web前端 > js教程 > 主體

vue中.vue檔解析步驟詳解

php中世界最好的语言
發布: 2018-04-27 10:09:34
原創
2780 人瀏覽過

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

我們平常寫的 .vue 檔案稱為 SFC(Single File Components),本文介紹將 SFC 解析為 descriptor 這個過程在 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中文網其它相關文章!
推薦閱讀:

######vue webpack使用案例詳解################react 配合antd元件做出後台系統#### ###########Vue.js中.native修飾詞使用詳解##########

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

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!