/* @flow */

import { genHandlers } from './events'
import { baseWarn, pluckModuleFunction } from '../helpers'
import baseDirectives from '../directives/index'
import { camelize } from 'shared/util' // configurable state
let warn
let transforms
let dataGenFns
let platformDirectives
let staticRenderFns
let onceCount
let currentOptions export function generate (
ast: ASTElement | void,
options: CompilerOptions
): {
render: string,
staticRenderFns: Array<string>
} {
// save previous staticRenderFns so generate calls can be nested
const prevStaticRenderFns: Array<string> = staticRenderFns
const currentStaticRenderFns: Array<string> = staticRenderFns = []
const prevOnceCount = onceCount
onceCount = 0
currentOptions = options
warn = options.warn || baseWarn
transforms = pluckModuleFunction(options.modules, 'transformCode')
dataGenFns = pluckModuleFunction(options.modules, 'genData')
platformDirectives = options.directives || {}
const code = ast ? genElement(ast) : '_h("div")'
staticRenderFns = prevStaticRenderFns
onceCount = prevOnceCount
return {
render: `with(this){return ${code}}`,
staticRenderFns: currentStaticRenderFns
}
} function genElement (el: ASTElement): string {
if (el.staticRoot && !el.staticProcessed) {
return genStatic(el)
} else if (el.once && !el.onceProcessed) {
return genOnce(el)
} else if (el.for && !el.forProcessed) {
return genFor(el)
} else if (el.if && !el.ifProcessed) {
return genIf(el)
} else if (el.tag === 'template' && !el.slotTarget) {
return genChildren(el) || 'void 0'
} else if (el.tag === 'slot') {
return genSlot(el)
} else {
// component or element
let code
if (el.component) {
code = genComponent(el.component, el)
} else {
const data = el.plain ? undefined : genData(el) const children = el.inlineTemplate ? null : genChildren(el)
code = `_h('${el.tag}'${
data ? `,${data}` : '' // data
}${
children ? `,${children}` : '' // children
})`
}
// module transforms
for (let i = 0; i < transforms.length; i++) {
code = transforms[i](el, code)
}
return code
}
} // hoist static sub-trees out
function genStatic (el: ASTElement): string {
el.staticProcessed = true
staticRenderFns.push(`with(this){return ${genElement(el)}}`)
return `_m(${staticRenderFns.length - 1}${el.staticInFor ? ',true' : ''})`
} // v-once
function genOnce (el: ASTElement): string {
el.onceProcessed = true
if (el.if && !el.ifProcessed) {
return genIf(el)
} else if (el.staticInFor) {
let key = ''
let parent = el.parent
while (parent) {
if (parent.for) {
key = parent.key
break
}
parent = parent.parent
}
if (!key) {
process.env.NODE_ENV !== 'production' && warn(
`v-once can only be used inside v-for that is keyed. `
)
return genElement(el)
}
return `_o(${genElement(el)},${onceCount++}${key ? `,${key}` : ``})`
} else {
return genStatic(el)
}
} function genIf (el: any): string {
el.ifProcessed = true // avoid recursion
return genIfConditions(el.conditions)
} function genIfConditions (conditions: ASTIfConditions): string {
if (!conditions.length) {
return '_e()'
} var condition = conditions.shift()
if (condition.exp) {
return `(${condition.exp})?${genTernaryExp(condition.block)}:${genIfConditions(conditions)}`
} else {
return `${genTernaryExp(condition.block)}`
} // v-if with v-once shuold generate code like (a)?_m(0):_m(1)
function genTernaryExp (el) {
return el.once ? genOnce(el) : genElement(el)
}
} function genFor (el: any): string {
const exp = el.for
const alias = el.alias
const iterator1 = el.iterator1 ? `,${el.iterator1}` : ''
const iterator2 = el.iterator2 ? `,${el.iterator2}` : ''
el.forProcessed = true // avoid recursion
return `_l((${exp}),` +
`function(${alias}${iterator1}${iterator2}){` +
`return ${genElement(el)}` +
'})'
} function genData (el: ASTElement): string {
let data = '{' // directives first.
// directives may mutate the el's other properties before they are generated.
const dirs = genDirectives(el)
if (dirs) data += dirs + ',' // key
if (el.key) {
data += `key:${el.key},`
}
// ref
if (el.ref) {
data += `ref:${el.ref},`
}
if (el.refInFor) {
data += `refInFor:true,`
}
// record original tag name for components using "is" attribute
if (el.component) {
data += `tag:"${el.tag}",`
}
// module data generation functions
for (let i = 0; i < dataGenFns.length; i++) {
data += dataGenFns[i](el)
}
// attributes
if (el.attrs) {
data += `attrs:{${genProps(el.attrs)}},`
}
// DOM props
if (el.props) {
data += `domProps:{${genProps(el.props)}},`
}
// event handlers
if (el.events) {
data += `${genHandlers(el.events)},`
}
if (el.nativeEvents) {
data += `${genHandlers(el.nativeEvents, true)},`
}
// slot target
if (el.slotTarget) {
data += `slot:${el.slotTarget},`
}
// scoped slots
if (el.scopedSlots) {
data += `${genScopedSlots(el.scopedSlots)},`
}
// inline-template
if (el.inlineTemplate) {
const inlineTemplate = genInlineTemplate(el)
if (inlineTemplate) {
data += `${inlineTemplate},`
}
}
data = data.replace(/,$/, '') + '}'
// v-bind data wrap
if (el.wrapData) {
data = el.wrapData(data)
}
return data
} function genDirectives (el: ASTElement): string | void {
const dirs = el.directives
if (!dirs) return
let res = 'directives:['
let hasRuntime = false
let i, l, dir, needRuntime
for (i = 0, l = dirs.length; i < l; i++) {
dir = dirs[i]
needRuntime = true
const gen = platformDirectives[dir.name] || baseDirectives[dir.name]
if (gen) {
// compile-time directive that manipulates AST.
// returns true if it also needs a runtime counterpart.
needRuntime = !!gen(el, dir, warn)
}
if (needRuntime) {
hasRuntime = true
res += `{name:"${dir.name}",rawName:"${dir.rawName}"${
dir.value ? `,value:(${dir.value}),expression:${JSON.stringify(dir.value)}` : ''
}${
dir.arg ? `,arg:"${dir.arg}"` : ''
}${
dir.modifiers ? `,modifiers:${JSON.stringify(dir.modifiers)}` : ''
}},`
}
}
if (hasRuntime) {
return res.slice(0, -1) + ']'
}
} function genInlineTemplate (el: ASTElement): ?string {
const ast = el.children[0]
if (process.env.NODE_ENV !== 'production' && (
el.children.length > 1 || ast.type !== 1
)) {
warn('Inline-template components must have exactly one child element.')
}
if (ast.type === 1) {
const inlineRenderFns = generate(ast, currentOptions)
return `inlineTemplate:{render:function(){${
inlineRenderFns.render
}},staticRenderFns:[${
inlineRenderFns.staticRenderFns.map(code => `function(){${code}}`).join(',')
}]}`
}
} function genScopedSlots (slots) {
return `scopedSlots:{${
Object.keys(slots).map(key => genScopedSlot(key, slots[key])).join(',')
}}`
} function genScopedSlot (key: string, el: ASTElement) {
return `${key}:function(${String(el.attrsMap.scope)}){` +
`return ${el.tag === 'template'
? genChildren(el) || 'void 0'
: genElement(el)
}}`
} function genChildren (el: ASTElement): string | void {
if (el.children.length) {
return '[' + el.children.map(genNode).join(',') + ']'
}
} function genNode (node: ASTNode) {
if (node.type === 1) {
return genElement(node)
} else {
return genText(node)
}
} function genText (text: ASTText | ASTExpression): string {
return text.type === 2
? text.expression // no need for () because already wrapped in _s()
: transformSpecialNewlines(JSON.stringify(text.text))
} function genSlot (el: ASTElement): string {
const slotName = el.slotName || '"default"'
const children = genChildren(el)
return `_t(${slotName}${
children ? `,${children}` : ''
}${
el.attrs ? `${children ? '' : ',null'},{${
el.attrs.map(a => `${camelize(a.name)}:${a.value}`).join(',')
}}` : ''
})`
} // componentName is el.component, take it as argument to shun flow's pessimistic refinement
function genComponent (componentName, el): string {
const children = el.inlineTemplate ? null : genChildren(el)
return `_h(${componentName},${genData(el)}${
children ? `,${children}` : ''
})`
} function genProps (props: Array<{ name: string, value: string }>): string {
let res = ''
for (let i = 0; i < props.length; i++) {
const prop = props[i]
res += `"${prop.name}":${transformSpecialNewlines(prop.value)},`
}
return res.slice(0, -1)
} // #3895, #4268
function transformSpecialNewlines (text: string): string {
return text
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
}

vue.js 源代码学习笔记 ----- codegen.js的更多相关文章

  1. vue.js 源代码学习笔记 ----- html-parse.js

    /** * Not type-checking this file because it's mostly vendor code. */ /*! * HTML Parser By John Resi ...

  2. vue.js 源代码学习笔记 ----- helpers.js

    /* @flow */ import { parseFilters } from './parser/filter-parser' export function baseWarn (msg: str ...

  3. vue.js 源代码学习笔记 ----- codegenEvents.js

    /* @flow */ const fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/ const simplePathRE = / ...

  4. vue.js 源代码学习笔记 ----- fillter-parse.js

    /* @flow */ export function parseFilters (exp: string): string { let inSingle = false let inDouble = ...

  5. vue.js 源代码学习笔记 ----- text-parse.js

    /* @flow */ import { cached } from 'shared/util' import { parseFilters } from './filter-parser' //找到 ...

  6. vue.js 源代码学习笔记 ----- 工具方法 lang

    /* @flow */ // Object.freeze 使得这个对象不能增加属性, 修改属性, 这样就保证了这个对象在任何时候都是空的 export const emptyObject = Obje ...

  7. vue.js 源代码学习笔记 ----- 工具方法 env

    /* @flow */ /* globals MutationObserver */ import { noop } from 'shared/util' // can we use __proto_ ...

  8. vue.js 源代码学习笔记 ----- 工具方法 share

    /* @flow */ /** * Convert a value to a string that is actually rendered. { .. } [ .. ] 2 => '' */ ...

  9. vue.js 源代码学习笔记 ----- instance render

    /* @flow */ import { warn, nextTick, toNumber, _toString, looseEqual, emptyObject, handleError, loos ...

随机推荐

  1. IOS 自己定义UITableView

    依据不同须要,须要使用tableview的结构,可是里面每个cell,又须要自己的样式.所以学习了一下如何把自定义的cell加到tableview里面 首先要自己创建一个类,继承UITableView ...

  2. Visual Studio 2017企业版 Enterprise 注册码 专业版Professional 激活码key

    Visual Studio 2017(VS2017) 企业版 Enterprise 注册码:NJVYC-BMHX2-G77MM-4XJMR-6Q8QFVisual Studio 2017(VS2017 ...

  3. PID参数调整的口诀

    PID参数调整的口诀:参数整定找最佳,从小到大顺序查先是比例后积分,最后再把微分加曲线振荡很频繁,比例度盘要放大曲线漂浮绕大湾,比例度盘往小扳曲线偏离回复慢,积分时间往下降曲线波动周期长,积分时间再加 ...

  4. Django model中数据批量导入bulk_create()

    在Django中需要向数据库中插入多条数据(list).使用如下方法,每次save()的时候都会访问一次数据库.导致性能问题: for i in resultlist: p = Account(nam ...

  5. 模块讲解----反射 (基于web路由的反射)

    一.反射的实际案例: def main(): menu = ''' 1.账户信息 2.还款 3.取款 4.转账 5.账单 ''' menu_dic = { ':account_info, ':repa ...

  6. tar 压缩解压命令详解

    tar -c: 建立压缩档案-x:解压-t:查看内容-r:向压缩归档文件末尾追加文件-u:更新原压缩包中的文件 这五个是独立的命令,压缩解压都要用到其中一个,可以和别的命令连用但只能用其中一个.下面的 ...

  7. G.Finding the Radius for an Inserted Circle 2017 ACM-ICPC 亚洲区(南宁赛区)网络赛

    地址:https://nanti.jisuanke.com/t/17314 题目: Three circles C_{a}C​a​​, C_{b}C​b​​, and C_{c}C​c​​, all ...

  8. A Practical Guide to Support Vector Classi cation

    <A Practical Guide to Support Vector Classication>是一篇libSVM使用入门教程以及一些实用技巧. 1. Basic Kernels: ( ...

  9. postgresql常用操作

    需要安装的软件包: apt-get install postgresql postgresql-client-9.1 postgresql-common postgresql-9.1 postgres ...

  10. ubuntu16.04安装tensorflow官方教程与机器学习资料【学习笔记】

    tensorflow官网有官方的安装教程:https://www.tensorflow.org/install/install_linux google的机器学习官方快速入门教程:https://de ...