欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue2從template到render模板編譯入口詳解

 更新時間:2022年08月22日 11:10:17   作者:qb  
這篇文章主要為大家介紹了vue2從template到render模板編譯入口詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

正文

在vue的渲染過程中,渲染核心邏輯是vm._update(vm._render(), hydrating),通過vm._render的執(zhí)行獲取到vNode,再通過vm._update的執(zhí)行來將vNode渲染成真實視圖。

其中,render函數(shù)的來源是:

(1)用戶手寫;

(2)通過vue-loader引入的時候進行轉換;

(3)通過compileToFunctions將template進行處理產(chǎn)生。

開發(fā)過程中主要以template的方式進行代碼的編寫,這里主要梳理compileToFunctions的方法。

1、template:模板獲取

在src/platforms/web/entry-runtime-with-compiler.js中在vue的原型上定義了$mount:

const idToTemplate = cached(id => {
  const el = query(id)
  return el && el.innerHTML
})
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
  el?: string | Element,
  hydrating?: boolean
): Component {
  el = el && query(el)
  /* istanbul ignore if */
  if (el === document.body || el === document.documentElement) {
    process.env.NODE_ENV !== 'production' && warn(
      `Do not mount Vue to <html> or <body> - mount to normal elements instead.`
    )
    return this
  }
  const options = this.$options
  // resolve template/el and convert to render function
  if (!options.render) {
    let template = options.template
    if (template) {
      if (typeof template === 'string') {
        if (template.charAt(0) === '#') {
          template = idToTemplate(template)
          /* istanbul ignore if */
          if (process.env.NODE_ENV !== 'production' && !template) {
            warn(
              `Template element not found or is empty: ${options.template}`,
              this
            )
          }
        }
      } else if (template.nodeType) {
        template = template.innerHTML
      } else {
        if (process.env.NODE_ENV !== 'production') {
          warn('invalid template option:' + template, this)
        }
        return this
      }
    } else if (el) {
      template = getOuterHTML(el)
    }
    if (template) {
      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile')
      }
      const { render, staticRenderFns } = compileToFunctions(template, {
        outputSourceRange: process.env.NODE_ENV !== 'production',
        shouldDecodeNewlines,
        shouldDecodeNewlinesForHref,
        delimiters: options.delimiters,
        comments: options.comments
      }, this)
      options.render = render
      options.staticRenderFns = staticRenderFns
      /* istanbul ignore if */
      if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
        mark('compile end')
        measure(`vue ${this._name} compile`, 'compile', 'compile end')
      }
    }
  }
  return mount.call(this, el, hydrating)
}
/**
 * Get outerHTML of elements, taking care
 * of SVG elements in IE as well.
 */
function getOuterHTML (el: Element): string {
  if (el.outerHTML) {
    return el.outerHTML
  } else {
    const container = document.createElement('div')
    container.appendChild(el.cloneNode(true))
    return container.innerHTML
  }
}

在沒有編寫render時候才會去獲取template并進行編譯,獲取方式有

  • 在傳入的參數(shù)中獲取options.template
  • 如果是真實節(jié)點則獲取其innerHTML
  • 以上都不滿足則通過或者el.outerhTML的方式獲取

獲取到template后通過compileToFunctions的方式進行編譯,這里是編譯的入口。

2、createCompiler:核心參數(shù)

在src/platforms/web/compile/index.js中調用了createCompiler:

import { baseOptions } from './options'
import { createCompiler } from 'compiler/index'
const { compile, compileToFunctions } = createCompiler(baseOptions)
export { compile, compileToFunctions }

這里將baseOptions作為基礎參數(shù)傳入,在src/complile/index.js中定義了createCompiler:

import { parse } from './parser/index'
import { optimize } from './optimizer'
import { generate } from './codegen/index'
import { createCompilerCreator } from './create-compiler'
export const createCompiler = createCompilerCreator(function baseCompile (
  template: string,
  options: CompilerOptions
): CompiledResult {
  const ast = parse(template.trim(), options)
  if (options.optimize !== false) {
    optimize(ast, options)
  }
  const code = generate(ast, options)
  return {
    ast,
    render: code.render,
    staticRenderFns: code.staticRenderFns
  }
})

這里定義了baseCompile核心參數(shù),主要目的是進行ast的獲取、ast的優(yōu)化和code的拼接。并將baseCompile作為參數(shù)傳入執(zhí)行了createCompilerCreator:

export function createCompilerCreator (baseCompile: Function): Function {
  return function createCompiler (baseOptions: CompilerOptions) {
    function compile (
      template: string,
      options?: CompilerOptions
    ): CompiledResult {
      // ...
    }
    return {
      compile,
      compileToFunctions: createCompileToFunctionFn(compile)
    }
  }
}

createCompiler就是createCompilerCreator的返回函數(shù),createCompiler中返回了compile和compileToFunctions,這里的compileToFunctions就是入口獲取render的函數(shù),由createCompileToFunctionFn(compile)執(zhí)行獲得。

再看createCompileToFunctionFn(compile):

3、createCompileToFunctionFn:緩存處理

function createFunction (code, errors) {
  try {
    return new Function(code)
  } catch (err) {
    errors.push({ err, code })
    return noop
  }
}
export function createCompileToFunctionFn (compile: Function): Function {
  const cache = Object.create(null)
  return function compileToFunctions (
    template: string,
    options?: CompilerOptions,
    vm?: Component
  ): CompiledFunctionResult {
    options = extend({}, options)
    const warn = options.warn || baseWarn
    delete options.warn
    /* istanbul ignore if */
    if (process.env.NODE_ENV !== 'production') {
      // detect possible CSP restriction
      try {
        new Function('return 1')
      } catch (e) {
        if (e.toString().match(/unsafe-eval|CSP/)) {
          warn(
            'It seems you are using the standalone build of Vue.js in an ' +
            'environment with Content Security Policy that prohibits unsafe-eval. ' +
            'The template compiler cannot work in this environment. Consider ' +
            'relaxing the policy to allow unsafe-eval or pre-compiling your ' +
            'templates into render functions.'
          )
        }
      }
    }
    // check cache
    const key = options.delimiters
      ? String(options.delimiters) + template
      : template
    if (cache[key]) {
      return cache[key]
    }
    // compile
    const compiled = compile(template, options)
    // ...
    // turn code into functions
    const res = {}
    const fnGenErrors = []
    res.render = createFunction(compiled.render, fnGenErrors)
    res.staticRenderFns = compiled.staticRenderFns.map(code => {
      return createFunction(code, fnGenErrors)
    })
    // check function generation errors.
    // this should only happen if there is a bug in the compiler itself.
    // mostly for codegen development use
    /* istanbul ignore if */
    if (process.env.NODE_ENV !== 'production') {
      if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) {
        warn(
          `Failed to generate render function:\n\n` +
          fnGenErrors.map(({ err, code }) => `${err.toString()} in\n\n$[code]\n`).join('\n'),
          vm
        )
      }
    }
    return (cache[key] = res)
  }
}

這里通過const cache = Object.create(null)的方式定義了緩存,返回的compileToFunctions函數(shù)中執(zhí)行return (cache[key] = res),通過閉包的方式進行了計算的重復利用。

如果當前環(huán)境支持new Function('return 1')則調用了createFunction將compiled.render通過new Function(code)進行可執(zhí)行代碼的轉換,否則進行提示(放寬環(huán)境執(zhí)行或預編譯當前模板)。

再看const compiled = compile(template, options):

4、compile:參數(shù)合并

function compile (
  template: string,
  options?: CompilerOptions
): CompiledResult {
  const finalOptions = Object.create(baseOptions)
  const errors = []
  const tips = []
  let warn = (msg, range, tip) => {
    (tip ? tips : errors).push(msg)
  }
  if (options) {
    if (process.env.NODE_ENV !== 'production' && options.outputSourceRange) {
      // $flow-disable-line
      const leadingSpaceLength = template.match(/^\s*/)[0].length
      warn = (msg, range, tip) => {
        const data: WarningMessage = { msg }
        if (range) {
          if (range.start != null) {
            data.start = range.start + leadingSpaceLength
          }
          if (range.end != null) {
            data.end = range.end + leadingSpaceLength
          }
        }
        (tip ? tips : errors).push(data)
      }
    }
    // merge custom modules
    if (options.modules) {
      finalOptions.modules =
        (baseOptions.modules || []).concat(options.modules)
    }
    // merge custom directives
    if (options.directives) {
      finalOptions.directives = extend(
        Object.create(baseOptions.directives || null),
        options.directives
      )
    }
    // copy other options
    for (const key in options) {
      if (key !== 'modules' && key !== 'directives') {
        finalOptions[key] = options[key]
      }
    }
  }
  finalOptions.warn = warn
  const compiled = baseCompile(template.trim(), finalOptions)
  if (process.env.NODE_ENV !== 'production') {
    detectErrors(compiled.ast, warn)
  }
  compiled.errors = errors
  compiled.tips = tips
  return compiled
}

這里的參數(shù)就是入口處獲取到的template,options就是入口處傳入的用戶參數(shù)

{ outputSourceRange: process.env.NODE_ENV !== 'production', shouldDecodeNewlines, shouldDecodeNewlinesForHref, delimiters: options.delimiters, comments: options.comments }

然后進行平臺參數(shù)和用戶參數(shù)的合并。最后將合并后的參數(shù)傳入并執(zhí)行

const compiled = baseCompile(template.trim(), finalOptions)

小結

vue模板編譯的真實入口是baseCompile,但是從Vue.prototype.$mount中的compileToFunctions方法開始進行了大量函數(shù)的嵌套,主要目的是通過閉包的方式進行緩存處理和平臺參數(shù)與用戶參數(shù)的合并。

以上就是vue2從template到render模板編譯入口詳解的詳細內(nèi)容,更多關于vue template render模板編譯的資料請關注腳本之家其它相關文章!

相關文章

  • Vue插值、表達式、分隔符、指令知識小結

    Vue插值、表達式、分隔符、指令知識小結

    這篇文章主要介紹了Vue插值、表達式、分隔符、指令的相關知識,文中給大家提到了去除vue插值表達式{{}}的方法,需要的朋友可以參考下
    2018-10-10
  • vant-list上拉加載onload事件觸發(fā)多次問題及解決

    vant-list上拉加載onload事件觸發(fā)多次問題及解決

    這篇文章主要介紹了vant-list上拉加載onload事件觸發(fā)多次問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-01-01
  • Vue實現(xiàn)全局的toast組件方式

    Vue實現(xiàn)全局的toast組件方式

    這篇文章主要介紹了Vue實現(xiàn)全局的toast組件方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • 解決vue項目打包后提示圖片文件路徑錯誤的問題

    解決vue項目打包后提示圖片文件路徑錯誤的問題

    這篇文章主要介紹了解決vue項目打包后提示圖片文件路徑錯誤的問題,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2018-07-07
  • vue實現(xiàn)的請求服務器端API接口示例

    vue實現(xiàn)的請求服務器端API接口示例

    這篇文章主要介紹了vue實現(xiàn)的請求服務器端API接口,結合實例形式分析了vue針對post、get、patch、put等請求的封裝與調用相關操作技巧,需要的朋友可以參考下
    2019-05-05
  • 詳解Vue如何將多個空格被合并顯示成一個空格

    詳解Vue如何將多個空格被合并顯示成一個空格

    這篇文章主要為大家詳細介紹了在Vue中如何將多個空格被合并顯示成一個空格,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
    2024-04-04
  • Vue3組件間傳值避坑方法指南

    Vue3組件間傳值避坑方法指南

    這篇文章主要為大家介紹了Vue3組件間傳值避坑方法指南,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-03-03
  • vue實現(xiàn)城市列表選擇功能

    vue實現(xiàn)城市列表選擇功能

    這篇文章主要介紹了vue實現(xiàn)城市列表選擇功能,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2018-07-07
  • vue 按鈕 權限控制介紹

    vue 按鈕 權限控制介紹

    這篇文章主要介紹了vue 按鈕 權限控制,在日常項目中,會碰到需要根據(jù)后臺接口返回的數(shù)據(jù),來判斷當前用戶的操作權限,必須當有刪除權限時,就顯示刪除按鈕,下面我們就來了解一下具體的解決方法,需要的朋友也可以參考一下
    2021-12-12
  • vue3關于RouterView插槽和過渡動效

    vue3關于RouterView插槽和過渡動效

    這篇文章主要介紹了vue3關于RouterView插槽和過渡動效,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-06-06

最新評論