vue2/packages/vue-template-compiler/build.js

5029 lines
122 KiB
JavaScript
Raw Normal View History

'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var entities = require('entities');
var deindent = _interopDefault(require('de-indent'));
2016-08-30 03:49:00 +08:00
/* */
/**
* Convert a value to a string that is actually rendered.
*/
2016-08-30 03:49:00 +08:00
function _toString (val) {
return val == null
? ''
: typeof val === 'object'
? JSON.stringify(val, null, 2)
: String(val)
}
/**
* Convert a input value to a number for persistence.
* If the conversion fails, return original string.
*/
2016-08-30 03:49:00 +08:00
function toNumber (val) {
var n = parseFloat(val, 10)
return (n || n === 0) ? n : val
}
/**
* Make a map and return a function for checking if a key
* is in that map.
*/
2016-08-30 03:49:00 +08:00
function makeMap (
str,
expectsLowerCase
) {
var map = Object.create(null)
var list = str.split(',')
for (var i = 0; i < list.length; i++) {
2016-08-30 03:49:00 +08:00
map[list[i]] = true
}
2016-08-30 03:49:00 +08:00
return expectsLowerCase
? function (val) { return map[val.toLowerCase()]; }
: function (val) { return map[val]; }
}
/**
* Check if a tag is a built-in tag.
*/
2016-08-30 03:49:00 +08:00
var isBuiltInTag = makeMap('slot,component', true)
/**
* Remove an item from an array
*/
2016-08-30 03:49:00 +08:00
function remove (arr, item) {
if (arr.length) {
2016-08-30 03:49:00 +08:00
var index = arr.indexOf(item)
if (index > -1) {
2016-08-30 03:49:00 +08:00
return arr.splice(index, 1)
}
}
}
/**
* Check whether the object has the property.
*/
2016-08-30 03:49:00 +08:00
var hasOwnProperty = Object.prototype.hasOwnProperty
function hasOwn (obj, key) {
return hasOwnProperty.call(obj, key)
}
/**
* Check if value is primitive
*/
2016-08-30 03:49:00 +08:00
function isPrimitive (value) {
return typeof value === 'string' || typeof value === 'number'
}
/**
* Create a cached version of a pure function.
*/
2016-08-30 03:49:00 +08:00
function cached (fn) {
var cache = Object.create(null)
return function cachedFn (str) {
var hit = cache[str]
return hit || (cache[str] = fn(str))
}
}
/**
* Camelize a hyphen-delmited string.
*/
2016-08-30 03:49:00 +08:00
var camelizeRE = /-(\w)/g
var camelize = cached(function (str) {
2016-08-30 03:49:00 +08:00
return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; })
})
/**
* Capitalize a string.
*/
var capitalize = cached(function (str) {
2016-08-30 03:49:00 +08:00
return str.charAt(0).toUpperCase() + str.slice(1)
})
/**
* Hyphenate a camelCase string.
*/
2016-08-30 03:49:00 +08:00
var hyphenateRE = /([^-])([A-Z])/g
var hyphenate = cached(function (str) {
2016-08-30 03:49:00 +08:00
return str
.replace(hyphenateRE, '$1-$2')
.replace(hyphenateRE, '$1-$2')
.toLowerCase()
})
/**
* Simple bind, faster than native
*/
2016-08-30 03:49:00 +08:00
function bind (fn, ctx) {
function boundFn (a) {
var l = arguments.length
return l
? l > 1
? fn.apply(ctx, arguments)
: fn.call(ctx, a)
: fn.call(ctx)
}
// record original fn length
2016-08-30 03:49:00 +08:00
boundFn._length = fn.length
return boundFn
}
/**
* Convert an Array-like object to a real Array.
*/
2016-08-30 03:49:00 +08:00
function toArray (list, start) {
start = start || 0
var i = list.length - start
var ret = new Array(i)
while (i--) {
2016-08-30 03:49:00 +08:00
ret[i] = list[i + start]
}
2016-08-30 03:49:00 +08:00
return ret
}
/**
* Mix properties into target object.
*/
2016-08-30 03:49:00 +08:00
function extend (to, _from) {
for (var key in _from) {
to[key] = _from[key]
}
2016-08-30 03:49:00 +08:00
return to
}
/**
* Quick object check - this is primarily used to tell
* Objects from primitive values when we know the value
* is a JSON-compliant type.
*/
2016-08-30 03:49:00 +08:00
function isObject (obj) {
return obj !== null && typeof obj === 'object'
}
/**
* Strict object type check. Only returns true
* for plain JavaScript objects.
*/
2016-08-30 03:49:00 +08:00
var toString = Object.prototype.toString
var OBJECT_STRING = '[object Object]'
function isPlainObject (obj) {
return toString.call(obj) === OBJECT_STRING
}
/**
* Merge an Array of Objects into a single Object.
*/
2016-08-30 03:49:00 +08:00
function toObject (arr) {
var res = arr[0] || {}
for (var i = 1; i < arr.length; i++) {
if (arr[i]) {
2016-08-30 03:49:00 +08:00
extend(res, arr[i])
}
}
2016-08-30 03:49:00 +08:00
return res
}
/**
* Perform no operation.
*/
2016-08-30 03:49:00 +08:00
function noop () {}
/**
* Always return false.
*/
2016-08-30 03:49:00 +08:00
var no = function () { return false; }
/**
* Generate a static keys string from compiler modules.
*/
2016-08-30 03:49:00 +08:00
function genStaticKeys (modules) {
return modules.reduce(function (keys, m) {
2016-08-30 03:49:00 +08:00
return keys.concat(m.staticKeys || [])
}, []).join(',')
}
2016-08-30 03:49:00 +08:00
/* */
var config = {
/**
* Option merge strategies (used in core/util/options)
*/
optionMergeStrategies: Object.create(null),
/**
* Whether to suppress warnings.
*/
silent: false,
/**
* Whether to enable devtools
*/
devtools: process.env.NODE_ENV !== 'production',
/**
* Error handler for watcher errors
*/
errorHandler: null,
/**
* Ignore certain custom elements
*/
ignoredElements: null,
/**
* Custom user key aliases for v-on
*/
keyCodes: Object.create(null),
/**
* Check if a tag is reserved so that it cannot be registered as a
* component. This is platform-dependent and may be overwritten.
*/
isReservedTag: no,
/**
* Check if a tag is an unknown element.
* Platform-dependent.
*/
isUnknownElement: no,
/**
* Get the namespace of an element
*/
getTagNamespace: noop,
/**
* Check if an attribute must be bound using property, e.g. value
* Platform-dependent.
*/
mustUseProp: no,
/**
* List of asset types that a component can own.
*/
2016-08-30 03:49:00 +08:00
_assetTypes: [
'component',
'directive',
'filter'
],
/**
* List of lifecycle hooks.
*/
2016-08-30 03:49:00 +08:00
_lifecycleHooks: [
'beforeCreate',
'created',
'beforeMount',
'mounted',
'beforeUpdate',
'updated',
'beforeDestroy',
'destroyed',
'activated',
'deactivated'
],
/**
* Max circular updates allowed in a scheduler flush cycle.
*/
_maxUpdateCount: 100,
/**
* Server rendering?
*/
_isServer: process.env.VUE_ENV === 'server'
2016-08-30 03:49:00 +08:00
}
2016-08-30 03:49:00 +08:00
var warn
var formatComponentName
if (process.env.NODE_ENV !== 'production') {
2016-08-30 03:49:00 +08:00
var hasConsole = typeof console !== 'undefined'
2016-08-30 03:49:00 +08:00
warn = function (msg, vm) {
if (hasConsole && (!config.silent)) {
console.error("[Vue warn]: " + msg + " " + (
vm ? formatLocation(formatComponentName(vm)) : ''
))
}
}
2016-08-30 03:49:00 +08:00
formatComponentName = function (vm) {
if (vm.$root === vm) {
return 'root instance'
}
var name = vm._isVue
? vm.$options.name || vm.$options._componentTag
: vm.name
return name ? ("component <" + name + ">") : "anonymous component"
}
2016-08-30 03:49:00 +08:00
var formatLocation = function (str) {
if (str === 'anonymous component') {
str += " - use the \"name\" option for better debugging messages."
}
return ("(found in " + str + ")")
}
}
2016-08-30 03:49:00 +08:00
/* */
/**
* Check if a string starts with $ or _
*/
2016-08-30 03:49:00 +08:00
function isReserved (str) {
var c = (str + '').charCodeAt(0)
return c === 0x24 || c === 0x5F
}
/**
* Define a property.
*/
2016-08-30 03:49:00 +08:00
function def (obj, key, val, enumerable) {
Object.defineProperty(obj, key, {
value: val,
enumerable: !!enumerable,
writable: true,
configurable: true
2016-08-30 03:49:00 +08:00
})
}
/**
* Parse simple path.
*/
2016-08-30 03:49:00 +08:00
var bailRE = /[^\w\.\$]/
function parsePath (path) {
if (bailRE.test(path)) {
2016-08-30 03:49:00 +08:00
return
} else {
2016-08-30 03:49:00 +08:00
var segments = path.split('.')
return function (obj) {
for (var i = 0; i < segments.length; i++) {
if (!obj) return
obj = obj[segments[i]]
}
return obj
}
}
}
2016-08-30 03:49:00 +08:00
/* */
/* global MutationObserver */
// can we use __proto__?
2016-08-30 03:49:00 +08:00
var hasProto = '__proto__' in {}
// Browser environment sniffing
2016-08-30 03:49:00 +08:00
var inBrowser =
typeof window !== 'undefined' &&
Object.prototype.toString.call(window) !== '[object Object]'
// detect devtools
2016-08-30 03:49:00 +08:00
var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__
// UA sniffing for working around browser-specific quirks
2016-08-30 03:49:00 +08:00
var UA$1 = inBrowser && window.navigator.userAgent.toLowerCase()
var isIos = UA$1 && /(iphone|ipad|ipod|ios)/i.test(UA$1)
var iosVersionMatch = UA$1 && isIos && UA$1.match(/os ([\d_]+)/)
var iosVersion = iosVersionMatch && iosVersionMatch[1].split('_')
// MutationObserver is unreliable in iOS 9.3 UIWebView
// detecting it by checking presence of IndexedDB
// ref #3027
2016-08-30 03:49:00 +08:00
var hasMutationObserverBug =
iosVersion &&
Number(iosVersion[0]) >= 9 &&
Number(iosVersion[1]) >= 3 &&
!window.indexedDB
/**
* Defer a task to execute it asynchronously. Ideally this
* should be executed as a microtask, so we leverage
* MutationObserver if it's available, and fallback to
* setTimeout(0).
*
* @param {Function} cb
* @param {Object} ctx
*/
2016-08-30 03:49:00 +08:00
var nextTick = (function () {
var callbacks = []
var pending = false
var timerFunc
function nextTickHandler () {
pending = false
var copies = callbacks.slice(0)
callbacks = []
for (var i = 0; i < copies.length; i++) {
2016-08-30 03:49:00 +08:00
copies[i]()
}
}
/* istanbul ignore else */
if (typeof MutationObserver !== 'undefined' && !hasMutationObserverBug) {
2016-08-30 03:49:00 +08:00
var counter = 1
var observer = new MutationObserver(nextTickHandler)
var textNode = document.createTextNode(String(counter))
2016-08-21 02:04:54 +08:00
observer.observe(textNode, {
characterData: true
2016-08-30 03:49:00 +08:00
})
timerFunc = function () {
counter = (counter + 1) % 2
textNode.data = String(counter)
}
} else {
// webpack attempts to inject a shim for setImmediate
// if it is used as a global, so we have to work around that to
// avoid bundling unnecessary code.
2016-08-30 03:49:00 +08:00
var context = inBrowser
? window
: typeof global !== 'undefined' ? global : {}
timerFunc = context.setImmediate || setTimeout
}
return function (cb, ctx) {
2016-08-30 03:49:00 +08:00
var func = ctx
? function () { cb.call(ctx) }
: cb
callbacks.push(func)
if (pending) return
pending = true
timerFunc(nextTickHandler, 0)
}
})()
var _Set
/* istanbul ignore if */
if (typeof Set !== 'undefined' && /native code/.test(Set.toString())) {
// use native Set when available.
2016-08-30 03:49:00 +08:00
_Set = Set
} else {
// a non-standard Set polyfill that only works with primitive keys.
2016-08-30 03:49:00 +08:00
_Set = (function () {
function Set () {
this.set = Object.create(null)
}
2016-08-30 03:49:00 +08:00
Set.prototype.has = function has (key) {
return this.set[key] !== undefined
};
2016-08-30 03:49:00 +08:00
Set.prototype.add = function add (key) {
this.set[key] = 1
};
2016-08-30 03:49:00 +08:00
Set.prototype.clear = function clear () {
this.set = Object.create(null)
};
return Set;
2016-08-30 03:49:00 +08:00
}())
}
2016-08-30 03:49:00 +08:00
/* not type checking this file because flow doesn't play well with Proxy */
var hasProxy;
var proxyHandlers;
var initProxy;
if (process.env.NODE_ENV !== 'production') {
2016-08-30 03:49:00 +08:00
var allowedGlobals = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
'require' // for Webpack/Browserify
)
hasProxy =
typeof Proxy !== 'undefined' &&
Proxy.toString().match(/native code/)
proxyHandlers = {
has: function has (target, key) {
var has = key in target
var isAllowed = allowedGlobals(key) || key.charAt(0) === '_'
if (!has && !isAllowed) {
warn(
"Property or method \"" + key + "\" is not defined on the instance but " +
"referenced during render. Make sure to declare reactive data " +
"properties in the data option.",
target
)
}
2016-08-30 03:49:00 +08:00
return has || !isAllowed
}
}
2016-08-30 03:49:00 +08:00
initProxy = function initProxy (vm) {
if (hasProxy) {
vm._renderProxy = new Proxy(vm, proxyHandlers)
} else {
vm._renderProxy = vm
}
}
}
2016-08-30 03:49:00 +08:00
/* */
var uid$2 = 0
/**
* A dep is an observable that can have multiple
* directives subscribing to it.
*/
2016-08-30 03:49:00 +08:00
var Dep = function Dep () {
this.id = uid$2++
this.subs = []
};
2016-08-30 03:49:00 +08:00
Dep.prototype.addSub = function addSub (sub) {
this.subs.push(sub)
};
2016-08-30 03:49:00 +08:00
Dep.prototype.removeSub = function removeSub (sub) {
remove(this.subs, sub)
};
2016-08-30 03:49:00 +08:00
Dep.prototype.depend = function depend () {
if (Dep.target) {
Dep.target.addDep(this)
}
};
2016-08-30 03:49:00 +08:00
Dep.prototype.notify = function notify () {
// stablize the subscriber list first
var subs = this.subs.slice()
for (var i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
};
2016-08-30 03:49:00 +08:00
// the current target watcher being evaluated.
// this is globally unique because there could be only one
// watcher being evaluated at any time.
Dep.target = null
var targetStack = []
2016-08-30 03:49:00 +08:00
function pushTarget (_target) {
if (Dep.target) targetStack.push(Dep.target)
Dep.target = _target
}
2016-08-30 03:49:00 +08:00
function popTarget () {
Dep.target = targetStack.pop()
}
2016-08-30 03:49:00 +08:00
/* */
var queue = []
var has = {}
var circular = {}
var waiting = false
var flushing = false
var index = 0
/**
* Reset the scheduler's state.
*/
2016-08-30 03:49:00 +08:00
function resetSchedulerState () {
queue.length = 0
has = {}
if (process.env.NODE_ENV !== 'production') {
2016-08-30 03:49:00 +08:00
circular = {}
}
2016-08-30 03:49:00 +08:00
waiting = flushing = false
}
/**
* Flush both queues and run the watchers.
*/
2016-08-30 03:49:00 +08:00
function flushSchedulerQueue () {
flushing = true
// Sort queue before flush.
// This ensures that:
// 1. Components are updated from parent to child. (because parent is always
// created before the child)
// 2. A component's user watchers are run before its render watcher (because
// user watchers are created before the render watcher)
// 3. If a component is destroyed during a parent component's watcher run,
// its watchers can be skipped.
2016-08-30 03:49:00 +08:00
queue.sort(function (a, b) { return a.id - b.id; })
// do not cache length because more watchers might be pushed
// as we run existing watchers
for (index = 0; index < queue.length; index++) {
2016-08-30 03:49:00 +08:00
var watcher = queue[index]
var id = watcher.id
has[id] = null
watcher.run()
// in dev build, check and stop circular updates.
if (process.env.NODE_ENV !== 'production' && has[id] != null) {
2016-08-30 03:49:00 +08:00
circular[id] = (circular[id] || 0) + 1
if (circular[id] > config._maxUpdateCount) {
2016-08-30 03:49:00 +08:00
warn(
'You may have an infinite update loop ' + (
watcher.user
? ("in watcher with expression \"" + (watcher.expression) + "\"")
: "in a component render function."
),
watcher.vm
)
break
}
}
}
// devtool hook
/* istanbul ignore if */
if (devtools && config.devtools) {
2016-08-30 03:49:00 +08:00
devtools.emit('flush')
}
2016-08-30 03:49:00 +08:00
resetSchedulerState()
}
/**
* Push a watcher into the watcher queue.
* Jobs with duplicate IDs will be skipped unless it's
* pushed when the queue is being flushed.
*/
2016-08-30 03:49:00 +08:00
function queueWatcher (watcher) {
var id = watcher.id
if (has[id] == null) {
2016-08-30 03:49:00 +08:00
has[id] = true
if (!flushing) {
2016-08-30 03:49:00 +08:00
queue.push(watcher)
} else {
// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
2016-08-30 03:49:00 +08:00
var i = queue.length - 1
while (i >= 0 && queue[i].id > watcher.id) {
2016-08-30 03:49:00 +08:00
i--
}
2016-08-30 03:49:00 +08:00
queue.splice(Math.max(i, index) + 1, 0, watcher)
}
// queue the flush
if (!waiting) {
2016-08-30 03:49:00 +08:00
waiting = true
nextTick(flushSchedulerQueue)
}
}
}
2016-08-30 03:49:00 +08:00
/* */
var uid$1 = 0
/**
* A watcher parses an expression, collects dependencies,
* and fires callback when the expression value changes.
* This is used for both the $watch() api and directives.
*/
2016-08-30 03:49:00 +08:00
var Watcher = function Watcher (
vm,
expOrFn,
cb,
options
) {
if ( options === void 0 ) options = {};
this.vm = vm
vm._watchers.push(this)
// options
this.deep = !!options.deep
this.user = !!options.user
this.lazy = !!options.lazy
this.sync = !!options.sync
this.expression = expOrFn.toString()
this.cb = cb
this.id = ++uid$1 // uid for batching
this.active = true
this.dirty = this.lazy // for lazy watchers
this.deps = []
this.newDeps = []
this.depIds = new _Set()
this.newDepIds = new _Set()
// parse expression for getter
if (typeof expOrFn === 'function') {
this.getter = expOrFn
} else {
this.getter = parsePath(expOrFn)
if (!this.getter) {
this.getter = function () {}
process.env.NODE_ENV !== 'production' && warn(
"Failed watching path: \"" + expOrFn + "\" " +
'Watcher only accepts simple dot-delimited paths. ' +
'For full control, use a function instead.',
vm
)
}
}
this.value = this.lazy
? undefined
: this.get()
};
2016-08-30 03:49:00 +08:00
/**
* Evaluate the getter, and re-collect dependencies.
*/
Watcher.prototype.get = function get () {
pushTarget(this)
var value = this.getter.call(this.vm, this.vm)
// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
traverse(value)
}
popTarget()
this.cleanupDeps()
return value
};
2016-08-30 03:49:00 +08:00
/**
* Add a dependency to this directive.
*/
Watcher.prototype.addDep = function addDep (dep) {
var id = dep.id
if (!this.newDepIds.has(id)) {
this.newDepIds.add(id)
this.newDeps.push(dep)
if (!this.depIds.has(id)) {
dep.addSub(this)
}
2016-08-30 03:49:00 +08:00
}
};
2016-08-30 03:49:00 +08:00
/**
* Clean up for dependency collection.
*/
Watcher.prototype.cleanupDeps = function cleanupDeps () {
var this$1 = this;
2016-08-30 03:49:00 +08:00
var i = this.deps.length
while (i--) {
var dep = this$1.deps[i]
if (!this$1.newDepIds.has(dep.id)) {
dep.removeSub(this$1)
}
}
var tmp = this.depIds
this.depIds = this.newDepIds
this.newDepIds = tmp
this.newDepIds.clear()
tmp = this.deps
this.deps = this.newDeps
this.newDeps = tmp
this.newDeps.length = 0
};
2016-08-30 03:49:00 +08:00
/**
* Subscriber interface.
* Will be called when a dependency changes.
*/
Watcher.prototype.update = function update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
queueWatcher(this)
}
};
2016-08-30 03:49:00 +08:00
/**
* Scheduler job interface.
* Will be called by the scheduler.
*/
Watcher.prototype.run = function run () {
if (this.active) {
var value = this.get()
if (
value !== this.value ||
// Deep watchers and watchers on Object/Arrays should fire even
// when the value is the same, because the value may
// have mutated.
2016-08-30 03:49:00 +08:00
isObject(value) ||
this.deep
) {
// set new value
var oldValue = this.value
this.value = value
if (this.user) {
try {
this.cb.call(this.vm, value, oldValue)
} catch (e) {
process.env.NODE_ENV !== 'production' && warn(
("Error in watcher \"" + (this.expression) + "\""),
this.vm
)
/* istanbul ignore else */
if (config.errorHandler) {
config.errorHandler.call(null, e, this.vm)
} else {
throw e
}
}
2016-08-30 03:49:00 +08:00
} else {
this.cb.call(this.vm, value, oldValue)
}
}
2016-08-30 03:49:00 +08:00
}
};
2016-08-30 03:49:00 +08:00
/**
* Evaluate the value of the watcher.
* This only gets called for lazy watchers.
*/
Watcher.prototype.evaluate = function evaluate () {
this.value = this.get()
this.dirty = false
};
2016-08-30 03:49:00 +08:00
/**
* Depend on all deps collected by this watcher.
*/
Watcher.prototype.depend = function depend () {
var this$1 = this;
2016-08-30 03:49:00 +08:00
var i = this.deps.length
while (i--) {
this$1.deps[i].depend()
}
};
2016-08-30 03:49:00 +08:00
/**
* Remove self from all dependencies' subcriber list.
*/
Watcher.prototype.teardown = function teardown () {
var this$1 = this;
if (this.active) {
// remove self from vm's watcher list
// this is a somewhat expensive operation so we skip it
// if the vm is being destroyed or is performing a v-for
// re-render (the watcher list is then filtered by v-for).
if (!this.vm._isBeingDestroyed && !this.vm._vForRemoving) {
remove(this.vm._watchers, this)
}
var i = this.deps.length
while (i--) {
2016-08-30 03:49:00 +08:00
this$1.deps[i].removeSub(this$1)
}
2016-08-30 03:49:00 +08:00
this.active = false
}
};
2016-08-30 03:49:00 +08:00
/**
* Recursively traverse an object to evoke all converted
* getters, so that every nested property inside the object
* is collected as a "deep" dependency.
*/
var seenObjects = new _Set()
function traverse (val, seen) {
var i, keys
if (!seen) {
2016-08-30 03:49:00 +08:00
seen = seenObjects
seen.clear()
}
2016-08-30 03:49:00 +08:00
var isA = Array.isArray(val)
var isO = isObject(val)
if ((isA || isO) && Object.isExtensible(val)) {
if (val.__ob__) {
2016-08-30 03:49:00 +08:00
var depId = val.__ob__.dep.id
if (seen.has(depId)) {
2016-08-30 03:49:00 +08:00
return
} else {
2016-08-30 03:49:00 +08:00
seen.add(depId)
}
}
if (isA) {
2016-08-30 03:49:00 +08:00
i = val.length
while (i--) traverse(val[i], seen)
} else if (isO) {
2016-08-30 03:49:00 +08:00
keys = Object.keys(val)
i = keys.length
while (i--) traverse(val[keys[i]], seen)
}
}
}
2016-08-30 03:49:00 +08:00
/*
* not type checking this file because flow doesn't play well with
* dynamically accessing methods on Array prototype
*/
var arrayProto = Array.prototype
var arrayMethods = Object.create(arrayProto)
/**
* Intercept mutating methods and emit events
*/
2016-08-30 03:49:00 +08:00
;[
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
.forEach(function (method) {
// cache original method
2016-08-30 03:49:00 +08:00
var original = arrayProto[method]
def(arrayMethods, method, function mutator () {
var arguments$1 = arguments;
// avoid leaking arguments:
// http://jsperf.com/closure-with-arguments
2016-08-30 03:49:00 +08:00
var i = arguments.length
var args = new Array(i)
while (i--) {
2016-08-30 03:49:00 +08:00
args[i] = arguments$1[i]
}
2016-08-30 03:49:00 +08:00
var result = original.apply(this, args)
var ob = this.__ob__
var inserted
switch (method) {
case 'push':
2016-08-30 03:49:00 +08:00
inserted = args
break
case 'unshift':
2016-08-30 03:49:00 +08:00
inserted = args
break
case 'splice':
2016-08-30 03:49:00 +08:00
inserted = args.slice(2)
break
}
2016-08-30 03:49:00 +08:00
if (inserted) ob.observeArray(inserted)
// notify change
2016-08-30 03:49:00 +08:00
ob.dep.notify()
return result
})
})
2016-08-30 03:49:00 +08:00
/* */
var arrayKeys = Object.getOwnPropertyNames(arrayMethods)
/**
* By default, when a reactive property is set, the new value is
* also converted to become reactive. However when passing down props,
* we don't want to force conversion because the value may be a nested value
* under a frozen data structure. Converting it would defeat the optimization.
*/
var observerState = {
shouldConvert: true,
isSettingProps: false
2016-08-30 03:49:00 +08:00
}
/**
* Observer class that are attached to each observed
* object. Once attached, the observer converts target
* object's property keys into getter/setters that
* collect dependencies and dispatches updates.
*/
2016-08-30 03:49:00 +08:00
var Observer = function Observer (value) {
this.value = value
this.dep = new Dep()
this.vmCount = 0
def(value, '__ob__', this)
if (Array.isArray(value)) {
var augment = hasProto
? protoAugment
: copyAugment
augment(value, arrayMethods, arrayKeys)
this.observeArray(value)
} else {
this.walk(value)
}
2016-08-30 03:49:00 +08:00
};
2016-08-30 03:49:00 +08:00
/**
* Walk through each property and convert them into
* getter/setters. This method should only be called when
* value type is Object.
*/
Observer.prototype.walk = function walk (obj) {
var val = this.value
for (var key in obj) {
defineReactive(val, key, obj[key])
}
};
2016-08-30 03:49:00 +08:00
/**
* Observe a list of Array items.
*/
Observer.prototype.observeArray = function observeArray (items) {
for (var i = 0, l = items.length; i < l; i++) {
observe(items[i])
}
};
// helpers
/**
* Augment an target Object or Array by intercepting
* the prototype chain using __proto__
*/
2016-08-30 03:49:00 +08:00
function protoAugment (target, src) {
/* eslint-disable no-proto */
2016-08-30 03:49:00 +08:00
target.__proto__ = src
/* eslint-enable no-proto */
}
/**
* Augment an target Object or Array by defining
* hidden properties.
*
* istanbul ignore next
*/
2016-08-30 03:49:00 +08:00
function copyAugment (target, src, keys) {
for (var i = 0, l = keys.length; i < l; i++) {
2016-08-30 03:49:00 +08:00
var key = keys[i]
def(target, key, src[key])
}
}
/**
* Attempt to create an observer instance for a value,
* returns the new observer if successfully observed,
* or the existing observer if the value already has one.
*/
2016-08-30 03:49:00 +08:00
function observe (value) {
if (!isObject(value)) {
2016-08-30 03:49:00 +08:00
return
}
2016-08-30 03:49:00 +08:00
var ob
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
2016-08-30 03:49:00 +08:00
ob = value.__ob__
} else if (
observerState.shouldConvert &&
!config._isServer &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value)
}
2016-08-30 03:49:00 +08:00
return ob
}
/**
* Define a reactive property on an Object.
*/
2016-08-30 03:49:00 +08:00
function defineReactive (
obj,
key,
val,
customSetter
) {
var dep = new Dep()
2016-08-30 03:49:00 +08:00
var property = Object.getOwnPropertyDescriptor(obj, key)
if (property && property.configurable === false) {
2016-08-30 03:49:00 +08:00
return
}
// cater for pre-defined getter/setters
2016-08-30 03:49:00 +08:00
var getter = property && property.get
var setter = property && property.set
2016-08-30 03:49:00 +08:00
var childOb = observe(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
2016-08-30 03:49:00 +08:00
get: function reactiveGetter () {
var value = getter ? getter.call(obj) : val
if (Dep.target) {
2016-08-30 03:49:00 +08:00
dep.depend()
if (childOb) {
2016-08-30 03:49:00 +08:00
childOb.dep.depend()
}
if (Array.isArray(value)) {
for (var e, i = 0, l = value.length; i < l; i++) {
2016-08-30 03:49:00 +08:00
e = value[i]
e && e.__ob__ && e.__ob__.dep.depend()
}
}
}
2016-08-30 03:49:00 +08:00
return value
},
2016-08-30 03:49:00 +08:00
set: function reactiveSetter (newVal) {
var value = getter ? getter.call(obj) : val
if (newVal === value) {
2016-08-30 03:49:00 +08:00
return
}
if (process.env.NODE_ENV !== 'production' && customSetter) {
2016-08-30 03:49:00 +08:00
customSetter()
}
if (setter) {
2016-08-30 03:49:00 +08:00
setter.call(obj, newVal)
} else {
2016-08-30 03:49:00 +08:00
val = newVal
}
2016-08-30 03:49:00 +08:00
childOb = observe(newVal)
dep.notify()
}
2016-08-30 03:49:00 +08:00
})
}
/**
* Set a property on an object. Adds the new property and
* triggers change notification if the property doesn't
* already exist.
*/
2016-08-30 03:49:00 +08:00
function set (obj, key, val) {
if (Array.isArray(obj)) {
2016-08-30 03:49:00 +08:00
obj.splice(key, 1, val)
return val
}
if (hasOwn(obj, key)) {
2016-08-30 03:49:00 +08:00
obj[key] = val
return
}
2016-08-30 03:49:00 +08:00
var ob = obj.__ob__
if (obj._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && warn(
'Avoid adding reactive properties to a Vue instance or its root $data ' +
'at runtime - declare it upfront in the data option.'
)
return
}
if (!ob) {
2016-08-30 03:49:00 +08:00
obj[key] = val
return
}
2016-08-30 03:49:00 +08:00
defineReactive(ob.value, key, val)
ob.dep.notify()
return val
}
2016-08-21 02:04:54 +08:00
/**
* Delete a property and trigger change if necessary.
*/
2016-08-30 03:49:00 +08:00
function del (obj, key) {
var ob = obj.__ob__
if (obj._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && warn(
'Avoid deleting properties on a Vue instance or its root $data ' +
'- just set it to null.'
)
return
2016-08-21 02:04:54 +08:00
}
if (!hasOwn(obj, key)) {
2016-08-30 03:49:00 +08:00
return
2016-08-21 02:04:54 +08:00
}
2016-08-30 03:49:00 +08:00
delete obj[key]
2016-08-21 02:04:54 +08:00
if (!ob) {
2016-08-30 03:49:00 +08:00
return
2016-08-21 02:04:54 +08:00
}
2016-08-30 03:49:00 +08:00
ob.dep.notify()
2016-08-21 02:04:54 +08:00
}
2016-08-30 03:49:00 +08:00
/* */
function initState (vm) {
vm._watchers = []
initProps(vm)
initData(vm)
initComputed(vm)
initMethods(vm)
initWatch(vm)
}
2016-08-30 03:49:00 +08:00
function initProps (vm) {
var props = vm.$options.props
var propsData = vm.$options.propsData
if (props) {
2016-08-30 03:49:00 +08:00
var keys = vm.$options._propKeys = Object.keys(props)
var isRoot = !vm.$parent
// root instance props should be converted
2016-08-30 03:49:00 +08:00
observerState.shouldConvert = isRoot
var loop = function ( i ) {
var key = keys[i]
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
defineReactive(vm, key, validateProp(key, props, propsData, vm), function () {
if (vm.$parent && !observerState.isSettingProps) {
2016-08-30 03:49:00 +08:00
warn(
"Avoid mutating a prop directly since the value will be " +
"overwritten whenever the parent component re-renders. " +
"Instead, use a data or computed property based on the prop's " +
"value. Prop being mutated: \"" + key + "\"",
vm
)
}
2016-08-30 03:49:00 +08:00
})
} else {
2016-08-30 03:49:00 +08:00
defineReactive(vm, key, validateProp(key, props, propsData, vm))
}
};
2016-08-30 03:49:00 +08:00
for (var i = 0; i < keys.length; i++) loop( i );
observerState.shouldConvert = true
}
}
2016-08-30 03:49:00 +08:00
function initData (vm) {
var data = vm.$options.data
data = vm._data = typeof data === 'function'
? data.call(vm)
: data || {}
if (!isPlainObject(data)) {
2016-08-30 03:49:00 +08:00
data = {}
process.env.NODE_ENV !== 'production' && warn(
'data functions should return an object.',
vm
)
}
// proxy data on instance
2016-08-30 03:49:00 +08:00
var keys = Object.keys(data)
var props = vm.$options.props
var i = keys.length
while (i--) {
if (props && hasOwn(props, keys[i])) {
2016-08-30 03:49:00 +08:00
process.env.NODE_ENV !== 'production' && warn(
"The data property \"" + (keys[i]) + "\" is already declared as a prop. " +
"Use prop default value instead.",
vm
)
} else {
2016-08-30 03:49:00 +08:00
proxy(vm, keys[i])
}
}
// observe data
2016-08-30 03:49:00 +08:00
observe(data)
data.__ob__ && data.__ob__.vmCount++
}
var computedSharedDefinition = {
enumerable: true,
configurable: true,
get: noop,
set: noop
2016-08-30 03:49:00 +08:00
}
2016-08-30 03:49:00 +08:00
function initComputed (vm) {
var computed = vm.$options.computed
if (computed) {
2016-08-30 03:49:00 +08:00
for (var key in computed) {
var userDef = computed[key]
if (typeof userDef === 'function') {
2016-08-30 03:49:00 +08:00
computedSharedDefinition.get = makeComputedGetter(userDef, vm)
computedSharedDefinition.set = noop
} else {
2016-08-30 03:49:00 +08:00
computedSharedDefinition.get = userDef.get
? userDef.cache !== false
? makeComputedGetter(userDef.get, vm)
: bind(userDef.get, vm)
: noop
computedSharedDefinition.set = userDef.set
? bind(userDef.set, vm)
: noop
}
2016-08-30 03:49:00 +08:00
Object.defineProperty(vm, key, computedSharedDefinition)
}
}
}
2016-08-30 03:49:00 +08:00
function makeComputedGetter (getter, owner) {
var watcher = new Watcher(owner, getter, noop, {
lazy: true
2016-08-30 03:49:00 +08:00
})
return function computedGetter () {
if (watcher.dirty) {
2016-08-30 03:49:00 +08:00
watcher.evaluate()
}
if (Dep.target) {
2016-08-30 03:49:00 +08:00
watcher.depend()
}
2016-08-30 03:49:00 +08:00
return watcher.value
}
}
2016-08-30 03:49:00 +08:00
function initMethods (vm) {
var methods = vm.$options.methods
if (methods) {
2016-08-30 03:49:00 +08:00
for (var key in methods) {
vm[key] = bind(methods[key], vm)
}
}
}
2016-08-30 03:49:00 +08:00
function initWatch (vm) {
var watch = vm.$options.watch
if (watch) {
2016-08-30 03:49:00 +08:00
for (var key in watch) {
var handler = watch[key]
if (Array.isArray(handler)) {
for (var i = 0; i < handler.length; i++) {
2016-08-30 03:49:00 +08:00
createWatcher(vm, key, handler[i])
}
} else {
2016-08-30 03:49:00 +08:00
createWatcher(vm, key, handler)
}
}
}
}
2016-08-30 03:49:00 +08:00
function createWatcher (vm, key, handler) {
var options
if (isPlainObject(handler)) {
2016-08-30 03:49:00 +08:00
options = handler
handler = handler.handler
}
if (typeof handler === 'string') {
2016-08-30 03:49:00 +08:00
handler = vm[handler]
}
2016-08-30 03:49:00 +08:00
vm.$watch(key, handler, options)
}
2016-08-30 03:49:00 +08:00
function stateMixin (Vue) {
// flow somehow has problems with directly declared definition object
// when using Object.defineProperty, so we have to procedurally build up
// the object here.
2016-08-30 03:49:00 +08:00
var dataDef = {}
dataDef.get = function () {
2016-08-30 03:49:00 +08:00
return this._data
}
if (process.env.NODE_ENV !== 'production') {
dataDef.set = function (newData) {
2016-08-30 03:49:00 +08:00
warn(
'Avoid replacing instance root $data. ' +
'Use nested data properties instead.',
this
)
}
}
Object.defineProperty(Vue.prototype, '$data', dataDef)
Vue.prototype.$set = set
Vue.prototype.$delete = del
Vue.prototype.$watch = function (
expOrFn,
cb,
options
) {
var vm = this
options = options || {}
options.user = true
var watcher = new Watcher(vm, expOrFn, cb, options)
if (options.immediate) {
2016-08-30 03:49:00 +08:00
cb.call(vm, watcher.value)
}
2016-08-30 03:49:00 +08:00
return function unwatchFn () {
watcher.teardown()
}
}
}
2016-08-30 03:49:00 +08:00
function proxy (vm, key) {
if (!isReserved(key)) {
Object.defineProperty(vm, key, {
configurable: true,
enumerable: true,
2016-08-30 03:49:00 +08:00
get: function proxyGetter () {
return vm._data[key]
},
2016-08-30 03:49:00 +08:00
set: function proxySetter (val) {
vm._data[key] = val
}
2016-08-30 03:49:00 +08:00
})
}
}
/* */
var VNode = function VNode (
tag,
data,
children,
text,
elm,
ns,
context,
componentOptions
) {
this.tag = tag
this.data = data
this.children = children
this.text = text
this.elm = elm
this.ns = ns
this.context = context
this.key = data && data.key
this.componentOptions = componentOptions
this.child = undefined
this.parent = undefined
this.raw = false
this.isStatic = false
this.isRootInsert = true
this.isComment = false
this.isCloned = false
// apply construct hook.
// this is applied during render, before patch happens.
// unlike other hooks, this is applied on both client and server.
2016-08-30 03:49:00 +08:00
var constructHook = data && data.hook && data.hook.construct
if (constructHook) {
2016-08-30 03:49:00 +08:00
constructHook(this)
}
};
2016-08-30 03:49:00 +08:00
var emptyVNode = function () {
var node = new VNode()
node.text = ''
node.isComment = true
return node
}
// optimized shallow clone
// used for static nodes and slot nodes because they may be reused across
// multiple renders, cloning them avoids errors when DOM manipulations rely
// on their elm reference.
function cloneVNode (vnode) {
var cloned = new VNode(
vnode.tag,
vnode.data,
vnode.children,
vnode.text,
vnode.elm,
vnode.ns,
vnode.context,
vnode.componentOptions
)
cloned.isStatic = vnode.isStatic
cloned.key = vnode.key
cloned.isCloned = true
return cloned
}
function cloneVNodes (vnodes) {
var res = new Array(vnodes.length)
for (var i = 0; i < vnodes.length; i++) {
res[i] = cloneVNode(vnodes[i])
}
return res
}
/* */
function normalizeChildren (
children,
2016-09-08 19:29:47 +08:00
ns,
nestedIndex
2016-08-30 03:49:00 +08:00
) {
if (isPrimitive(children)) {
2016-08-30 03:49:00 +08:00
return [createTextVNode(children)]
}
if (Array.isArray(children)) {
2016-08-30 03:49:00 +08:00
var res = []
for (var i = 0, l = children.length; i < l; i++) {
2016-08-30 03:49:00 +08:00
var c = children[i]
var last = res[res.length - 1]
// nested
if (Array.isArray(c)) {
2016-09-08 19:29:47 +08:00
res.push.apply(res, normalizeChildren(c, ns, i))
} else if (isPrimitive(c)) {
if (last && last.text) {
2016-08-30 03:49:00 +08:00
last.text += String(c)
2016-08-06 06:14:22 +08:00
} else if (c !== '') {
// convert primitive to vnode
2016-08-30 03:49:00 +08:00
res.push(createTextVNode(c))
}
} else if (c instanceof VNode) {
if (c.text && last && last.text) {
2016-08-30 03:49:00 +08:00
last.text += c.text
} else {
// inherit parent namespace
if (ns) {
2016-08-30 03:49:00 +08:00
applyNS(c, ns)
}
2016-09-08 19:29:47 +08:00
// default key for nested array children (likely generated by v-for)
if (c.key == null && nestedIndex != null) {
c.key = "__vlist_" + nestedIndex + "_" + i + "__"
}
2016-08-30 03:49:00 +08:00
res.push(c)
}
}
}
2016-08-30 03:49:00 +08:00
return res
}
}
2016-08-30 03:49:00 +08:00
function createTextVNode (val) {
return new VNode(undefined, undefined, undefined, String(val))
}
2016-08-30 03:49:00 +08:00
function applyNS (vnode, ns) {
if (vnode.tag && !vnode.ns) {
2016-08-30 03:49:00 +08:00
vnode.ns = ns
if (vnode.children) {
for (var i = 0, l = vnode.children.length; i < l; i++) {
2016-08-30 03:49:00 +08:00
applyNS(vnode.children[i], ns)
}
}
}
}
2016-08-30 03:49:00 +08:00
function updateListeners (
on,
oldOn,
add,
remove
) {
var name, cur, old, fn, event, capture
for (name in on) {
2016-08-30 03:49:00 +08:00
cur = on[name]
old = oldOn[name]
2016-08-16 11:39:07 +08:00
if (!cur) {
2016-08-30 03:49:00 +08:00
process.env.NODE_ENV !== 'production' && warn(
("Handler for event \"" + name + "\" is undefined.")
)
2016-08-16 11:39:07 +08:00
} else if (!old) {
2016-08-30 03:49:00 +08:00
capture = name.charAt(0) === '!'
event = capture ? name.slice(1) : name
if (Array.isArray(cur)) {
2016-08-30 03:49:00 +08:00
add(event, (cur.invoker = arrInvoker(cur)), capture)
} else {
2016-08-30 03:49:00 +08:00
if (!cur.invoker) {
fn = cur
cur = on[name] = {}
cur.fn = fn
cur.invoker = fnInvoker(cur)
}
add(event, cur.invoker, capture)
}
2016-09-08 19:29:47 +08:00
} else if (cur !== old) {
if (Array.isArray(old)) {
old.length = cur.length
for (var i = 0; i < old.length; i++) old[i] = cur[i]
on[name] = old
} else {
old.fn = cur
on[name] = old
}
}
}
for (name in oldOn) {
if (!on[name]) {
2016-08-30 03:49:00 +08:00
event = name.charAt(0) === '!' ? name.slice(1) : name
remove(event, oldOn[name].invoker)
}
}
}
2016-08-30 03:49:00 +08:00
function arrInvoker (arr) {
return function (ev) {
2016-08-30 03:49:00 +08:00
var arguments$1 = arguments;
var single = arguments.length === 1
for (var i = 0; i < arr.length; i++) {
2016-08-30 03:49:00 +08:00
single ? arr[i](ev) : arr[i].apply(null, arguments$1)
}
2016-08-30 03:49:00 +08:00
}
}
2016-08-30 03:49:00 +08:00
function fnInvoker (o) {
return function (ev) {
2016-08-30 03:49:00 +08:00
var single = arguments.length === 1
single ? o.fn(ev) : o.fn.apply(null, arguments)
}
}
2016-08-30 03:49:00 +08:00
/* */
var activeInstance = null
2016-08-06 06:14:22 +08:00
2016-08-30 03:49:00 +08:00
function initLifecycle (vm) {
var options = vm.$options
// locate first non-abstract parent
2016-08-30 03:49:00 +08:00
var parent = options.parent
if (parent && !options.abstract) {
while (parent.$options.abstract && parent.$parent) {
2016-08-30 03:49:00 +08:00
parent = parent.$parent
}
2016-08-30 03:49:00 +08:00
parent.$children.push(vm)
}
2016-08-30 03:49:00 +08:00
vm.$parent = parent
vm.$root = parent ? parent.$root : vm
2016-08-30 03:49:00 +08:00
vm.$children = []
vm.$refs = {}
2016-08-30 03:49:00 +08:00
vm._watcher = null
vm._inactive = false
vm._isMounted = false
vm._isDestroyed = false
vm._isBeingDestroyed = false
}
2016-08-30 03:49:00 +08:00
function lifecycleMixin (Vue) {
Vue.prototype._mount = function (
el,
hydrating
) {
var vm = this
vm.$el = el
if (!vm.$options.render) {
2016-08-30 03:49:00 +08:00
vm.$options.render = emptyVNode
if (process.env.NODE_ENV !== 'production') {
/* istanbul ignore if */
if (vm.$options.template) {
2016-08-30 03:49:00 +08:00
warn(
'You are using the runtime-only build of Vue where the template ' +
'option is not available. Either pre-compile the templates into ' +
'render functions, or use the compiler-included build.',
vm
)
} else {
2016-08-30 03:49:00 +08:00
warn(
'Failed to mount component: template or render function not defined.',
vm
)
}
}
}
2016-08-30 03:49:00 +08:00
callHook(vm, 'beforeMount')
vm._watcher = new Watcher(vm, function () {
2016-08-30 03:49:00 +08:00
vm._update(vm._render(), hydrating)
}, noop)
hydrating = false
// root instance, call mounted on self
// mounted is called for child components in its inserted hook
if (vm.$root === vm) {
2016-08-30 03:49:00 +08:00
vm._isMounted = true
callHook(vm, 'mounted')
}
2016-08-30 03:49:00 +08:00
return vm
}
Vue.prototype._update = function (vnode, hydrating) {
2016-08-30 03:49:00 +08:00
var vm = this
if (vm._isMounted) {
2016-08-30 03:49:00 +08:00
callHook(vm, 'beforeUpdate')
}
2016-08-30 03:49:00 +08:00
var prevEl = vm.$el
var prevActiveInstance = activeInstance
activeInstance = vm
var prevVnode = vm._vnode
vm._vnode = vnode
2016-08-16 11:39:07 +08:00
if (!prevVnode) {
// Vue.prototype.__patch__ is injected in entry points
// based on the rendering backend used.
2016-08-30 03:49:00 +08:00
vm.$el = vm.__patch__(vm.$el, vnode, hydrating)
} else {
2016-08-30 03:49:00 +08:00
vm.$el = vm.__patch__(prevVnode, vnode)
}
2016-08-30 03:49:00 +08:00
activeInstance = prevActiveInstance
// update __vue__ reference
if (prevEl) {
2016-08-30 03:49:00 +08:00
prevEl.__vue__ = null
}
if (vm.$el) {
2016-08-30 03:49:00 +08:00
vm.$el.__vue__ = vm
}
// if parent is an HOC, update its $el as well
if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
2016-08-30 03:49:00 +08:00
vm.$parent.$el = vm.$el
}
if (vm._isMounted) {
2016-08-30 03:49:00 +08:00
callHook(vm, 'updated')
}
2016-08-30 03:49:00 +08:00
}
2016-08-30 03:49:00 +08:00
Vue.prototype._updateFromParent = function (
propsData,
listeners,
parentVnode,
renderChildren
) {
var vm = this
var hasChildren = !!(vm.$options._renderChildren || renderChildren)
vm.$options._parentVnode = parentVnode
vm.$options._renderChildren = renderChildren
// update props
if (propsData && vm.$options.props) {
2016-08-30 03:49:00 +08:00
observerState.shouldConvert = false
if (process.env.NODE_ENV !== 'production') {
2016-08-30 03:49:00 +08:00
observerState.isSettingProps = true
}
2016-08-30 03:49:00 +08:00
var propKeys = vm.$options._propKeys || []
for (var i = 0; i < propKeys.length; i++) {
2016-08-30 03:49:00 +08:00
var key = propKeys[i]
vm[key] = validateProp(key, vm.$options.props, propsData, vm)
}
2016-08-30 03:49:00 +08:00
observerState.shouldConvert = true
if (process.env.NODE_ENV !== 'production') {
2016-08-30 03:49:00 +08:00
observerState.isSettingProps = false
}
}
// update listeners
if (listeners) {
2016-08-30 03:49:00 +08:00
var oldListeners = vm.$options._parentListeners
vm.$options._parentListeners = listeners
vm._updateListeners(listeners, oldListeners)
}
2016-08-10 12:55:30 +08:00
// resolve slots + force update if has children
2016-08-06 06:14:22 +08:00
if (hasChildren) {
2016-08-30 03:49:00 +08:00
vm.$slots = resolveSlots(renderChildren)
vm.$forceUpdate()
2016-08-06 06:14:22 +08:00
}
2016-08-30 03:49:00 +08:00
}
Vue.prototype.$forceUpdate = function () {
2016-08-30 03:49:00 +08:00
var vm = this
if (vm._watcher) {
2016-08-30 03:49:00 +08:00
vm._watcher.update()
}
2016-08-30 03:49:00 +08:00
}
Vue.prototype.$destroy = function () {
2016-08-30 03:49:00 +08:00
var vm = this
if (vm._isBeingDestroyed) {
2016-08-30 03:49:00 +08:00
return
}
2016-08-30 03:49:00 +08:00
callHook(vm, 'beforeDestroy')
vm._isBeingDestroyed = true
// remove self from parent
2016-08-30 03:49:00 +08:00
var parent = vm.$parent
if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) {
2016-08-30 03:49:00 +08:00
remove(parent.$children, vm)
}
// teardown watchers
if (vm._watcher) {
2016-08-30 03:49:00 +08:00
vm._watcher.teardown()
}
2016-08-30 03:49:00 +08:00
var i = vm._watchers.length
while (i--) {
2016-08-30 03:49:00 +08:00
vm._watchers[i].teardown()
}
// remove reference from data ob
// frozen object may not have observer.
if (vm._data.__ob__) {
2016-08-30 03:49:00 +08:00
vm._data.__ob__.vmCount--
}
// call the last hook...
2016-08-30 03:49:00 +08:00
vm._isDestroyed = true
callHook(vm, 'destroyed')
// turn off all instance listeners.
2016-08-30 03:49:00 +08:00
vm.$off()
// remove __vue__ reference
if (vm.$el) {
2016-08-30 03:49:00 +08:00
vm.$el.__vue__ = null
}
2016-08-30 03:49:00 +08:00
}
}
2016-08-30 03:49:00 +08:00
function callHook (vm, hook) {
var handlers = vm.$options[hook]
if (handlers) {
for (var i = 0, j = handlers.length; i < j; i++) {
2016-08-30 03:49:00 +08:00
handlers[i].call(vm)
}
}
2016-08-30 03:49:00 +08:00
vm.$emit('hook:' + hook)
}
2016-08-30 03:49:00 +08:00
/* */
var hooks = { init: init, prepatch: prepatch, insert: insert, destroy: destroy }
var hooksToMerge = Object.keys(hooks)
2016-08-30 03:49:00 +08:00
function createComponent (
Ctor,
data,
context,
children,
tag
) {
if (!Ctor) {
2016-08-30 03:49:00 +08:00
return
}
if (isObject(Ctor)) {
2016-08-30 03:49:00 +08:00
Ctor = Vue.extend(Ctor)
}
if (typeof Ctor !== 'function') {
if (process.env.NODE_ENV !== 'production') {
2016-08-30 03:49:00 +08:00
warn(("Invalid Component definition: " + (String(Ctor))), context)
}
2016-08-30 03:49:00 +08:00
return
}
// async component
if (!Ctor.cid) {
if (Ctor.resolved) {
2016-08-30 03:49:00 +08:00
Ctor = Ctor.resolved
} else {
Ctor = resolveAsyncComponent(Ctor, function () {
// it's ok to queue this on every render because
2016-08-06 06:14:22 +08:00
// $forceUpdate is buffered by the scheduler.
2016-08-30 03:49:00 +08:00
context.$forceUpdate()
})
if (!Ctor) {
// return nothing if this is indeed an async component
// wait for the callback to trigger parent update.
2016-08-30 03:49:00 +08:00
return
}
}
}
2016-08-30 03:49:00 +08:00
data = data || {}
// extract props
2016-08-30 03:49:00 +08:00
var propsData = extractProps(data, Ctor)
// functional component
if (Ctor.options.functional) {
2016-08-30 03:49:00 +08:00
return createFunctionalComponent(Ctor, propsData, data, context, children)
}
// extract listeners, since these needs to be treated as
// child component listeners instead of DOM listeners
2016-08-30 03:49:00 +08:00
var listeners = data.on
// replace with listeners with .native modifier
2016-08-30 03:49:00 +08:00
data.on = data.nativeOn
2016-07-27 12:25:41 +08:00
if (Ctor.options.abstract) {
// abstract components do not keep anything
// other than props & listeners
2016-08-30 03:49:00 +08:00
data = {}
2016-07-27 12:25:41 +08:00
}
// merge component management hooks onto the placeholder node
2016-08-30 03:49:00 +08:00
mergeHooks(data)
2016-07-27 12:25:41 +08:00
// return a placeholder vnode
2016-08-30 03:49:00 +08:00
var name = Ctor.options.name || tag
var vnode = new VNode(
("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')),
data, undefined, undefined, undefined, undefined, context,
{ Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children }
)
return vnode
}
function createFunctionalComponent (
Ctor,
propsData,
data,
context,
children
) {
var props = {}
var propOptions = Ctor.options.props
2016-08-21 02:04:54 +08:00
if (propOptions) {
for (var key in propOptions) {
2016-08-30 03:49:00 +08:00
props[key] = validateProp(key, propOptions, propsData)
2016-08-21 02:04:54 +08:00
}
}
2016-08-30 03:49:00 +08:00
return Ctor.options.render.call(
null,
context.$createElement,
{
props: props,
data: data,
parent: context,
children: normalizeChildren(children),
slots: function () { return resolveSlots(children); }
2016-08-21 02:04:54 +08:00
}
2016-08-30 03:49:00 +08:00
)
2016-08-21 02:04:54 +08:00
}
2016-08-30 03:49:00 +08:00
function createComponentInstanceForVnode (
vnode, // we know it's MountedComponentVNode but flow doesn't
parent // activeInstance in lifecycle state
) {
2016-08-30 03:49:00 +08:00
var vnodeComponentOptions = vnode.componentOptions
var options = {
_isComponent: true,
2016-08-06 06:14:22 +08:00
parent: parent,
propsData: vnodeComponentOptions.propsData,
_componentTag: vnodeComponentOptions.tag,
_parentVnode: vnode,
_parentListeners: vnodeComponentOptions.listeners,
_renderChildren: vnodeComponentOptions.children
2016-08-30 03:49:00 +08:00
}
// check inline-template render functions
2016-08-30 03:49:00 +08:00
var inlineTemplate = vnode.data.inlineTemplate
if (inlineTemplate) {
2016-08-30 03:49:00 +08:00
options.render = inlineTemplate.render
options.staticRenderFns = inlineTemplate.staticRenderFns
}
2016-08-30 03:49:00 +08:00
return new vnodeComponentOptions.Ctor(options)
}
2016-08-30 03:49:00 +08:00
function init (vnode, hydrating) {
2016-08-16 11:39:07 +08:00
if (!vnode.child || vnode.child._isDestroyed) {
2016-08-30 03:49:00 +08:00
var child = vnode.child = createComponentInstanceForVnode(vnode, activeInstance)
child.$mount(hydrating ? vnode.elm : undefined, hydrating)
}
}
2016-08-30 03:49:00 +08:00
function prepatch (
oldVnode,
vnode
) {
var options = vnode.componentOptions
var child = vnode.child = oldVnode.child
child._updateFromParent(
options.propsData, // updated props
options.listeners, // updated listeners
vnode, // new parent vnode
options.children // new children
)
}
2016-08-30 03:49:00 +08:00
function insert (vnode) {
if (!vnode.child._isMounted) {
2016-08-30 03:49:00 +08:00
vnode.child._isMounted = true
callHook(vnode.child, 'mounted')
}
if (vnode.data.keepAlive) {
2016-08-30 03:49:00 +08:00
vnode.child._inactive = false
callHook(vnode.child, 'activated')
}
}
2016-08-30 03:49:00 +08:00
function destroy (vnode) {
if (!vnode.child._isDestroyed) {
if (!vnode.data.keepAlive) {
2016-08-30 03:49:00 +08:00
vnode.child.$destroy()
} else {
2016-08-30 03:49:00 +08:00
vnode.child._inactive = true
callHook(vnode.child, 'deactivated')
}
}
}
2016-08-30 03:49:00 +08:00
function resolveAsyncComponent (
factory,
cb
) {
if (factory.requested) {
// pool callbacks
2016-08-30 03:49:00 +08:00
factory.pendingCallbacks.push(cb)
} else {
2016-08-30 03:49:00 +08:00
factory.requested = true
var cbs = factory.pendingCallbacks = [cb]
var sync = true
var resolve = function (res) {
if (isObject(res)) {
res = Vue.extend(res)
}
// cache resolved
factory.resolved = res
// invoke callbacks only if this is not a synchronous resolve
// (async resolves are shimmed as synchronous during SSR)
if (!sync) {
for (var i = 0, l = cbs.length; i < l; i++) {
cbs[i](res)
}
2016-08-30 03:49:00 +08:00
}
}
var reject = function (reason) {
process.env.NODE_ENV !== 'production' && warn(
"Failed to resolve async component: " + (String(factory)) +
(reason ? ("\nReason: " + reason) : '')
)
}
var res = factory(resolve, reject)
// handle promise
if (res && typeof res.then === 'function' && !factory.resolved) {
res.then(resolve, reject)
}
2016-08-30 03:49:00 +08:00
sync = false
// return in case resolved synchronously
return factory.resolved
}
}
2016-08-30 03:49:00 +08:00
function extractProps (data, Ctor) {
// we are only extrating raw values here.
// validation and default values are handled in the child
// component itself.
2016-08-30 03:49:00 +08:00
var propOptions = Ctor.options.props
if (!propOptions) {
2016-08-30 03:49:00 +08:00
return
}
2016-08-30 03:49:00 +08:00
var res = {}
var attrs = data.attrs;
var props = data.props;
var domProps = data.domProps;
2016-08-02 03:31:12 +08:00
if (attrs || props || domProps) {
for (var key in propOptions) {
2016-08-30 03:49:00 +08:00
var altKey = hyphenate(key)
checkProp(res, props, key, altKey, true) ||
checkProp(res, attrs, key, altKey) ||
checkProp(res, domProps, key, altKey)
}
}
2016-08-30 03:49:00 +08:00
return res
}
2016-08-30 03:49:00 +08:00
function checkProp (
res,
hash,
key,
altKey,
preserve
) {
if (hash) {
if (hasOwn(hash, key)) {
2016-08-30 03:49:00 +08:00
res[key] = hash[key]
if (!preserve) {
2016-08-30 03:49:00 +08:00
delete hash[key]
}
2016-08-30 03:49:00 +08:00
return true
} else if (hasOwn(hash, altKey)) {
2016-08-30 03:49:00 +08:00
res[key] = hash[altKey]
if (!preserve) {
2016-08-30 03:49:00 +08:00
delete hash[altKey]
}
2016-08-30 03:49:00 +08:00
return true
}
}
2016-08-30 03:49:00 +08:00
return false
}
2016-08-30 03:49:00 +08:00
function mergeHooks (data) {
if (!data.hook) {
2016-08-30 03:49:00 +08:00
data.hook = {}
}
for (var i = 0; i < hooksToMerge.length; i++) {
2016-08-30 03:49:00 +08:00
var key = hooksToMerge[i]
var fromParent = data.hook[key]
var ours = hooks[key]
data.hook[key] = fromParent ? mergeHook$1(ours, fromParent) : ours
}
}
2016-08-30 03:49:00 +08:00
function mergeHook$1 (a, b) {
// since all hooks have at most two args, use fixed args
// to avoid having to use fn.apply().
return function (_, __) {
2016-08-30 03:49:00 +08:00
a(_, __)
b(_, __)
}
}
2016-08-30 03:49:00 +08:00
/* */
// wrapper function for providing a more flexible interface
// without getting yelled at by flow
2016-08-30 03:49:00 +08:00
function createElement (
tag,
data,
children
) {
if (data && (Array.isArray(data) || typeof data !== 'object')) {
2016-08-30 03:49:00 +08:00
children = data
data = undefined
}
// make sure to use real instance instead of proxy as context
2016-08-30 03:49:00 +08:00
return _createElement(this._self, tag, data, children)
}
2016-08-30 03:49:00 +08:00
function _createElement (
context,
tag,
data,
children
) {
if (data && data.__ob__) {
2016-08-30 03:49:00 +08:00
process.env.NODE_ENV !== 'production' && warn(
"Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" +
'Always create fresh vnode data objects in each render!',
context
)
return
}
if (!tag) {
// in case of component :is set to falsy value
2016-08-30 03:49:00 +08:00
return emptyVNode()
}
if (typeof tag === 'string') {
2016-08-30 03:49:00 +08:00
var Ctor
var ns = config.getTagNamespace(tag)
if (config.isReservedTag(tag)) {
// platform built-in elements
2016-08-30 03:49:00 +08:00
return new VNode(
tag, data, normalizeChildren(children, ns),
undefined, undefined, ns, context
)
} else if ((Ctor = resolveAsset(context.$options, 'components', tag))) {
// component
2016-08-30 03:49:00 +08:00
return createComponent(Ctor, data, context, children, tag)
} else {
// unknown or unlisted namespaced elements
// check at runtime because it may get assigned a namespace when its
// parent normalizes children
2016-08-30 03:49:00 +08:00
return new VNode(
tag, data, normalizeChildren(children, ns),
undefined, undefined, ns, context
)
}
} else {
// direct component options / constructor
2016-08-30 03:49:00 +08:00
return createComponent(tag, data, context, children)
}
}
2016-08-30 03:49:00 +08:00
/* */
function initRender (vm) {
vm.$vnode = null // the placeholder node in parent tree
vm._vnode = null // the root of the child tree
vm._staticTrees = null
vm.$slots = resolveSlots(vm.$options._renderChildren)
// bind the public createElement fn to this instance
// so that we get proper render context inside it.
2016-08-30 03:49:00 +08:00
vm.$createElement = bind(createElement, vm)
if (vm.$options.el) {
2016-08-30 03:49:00 +08:00
vm.$mount(vm.$options.el)
}
}
2016-08-30 03:49:00 +08:00
function renderMixin (Vue) {
Vue.prototype.$nextTick = function (fn) {
2016-08-30 03:49:00 +08:00
nextTick(fn, this)
}
Vue.prototype._render = function () {
2016-08-30 03:49:00 +08:00
var vm = this
var ref = vm.$options;
var render = ref.render;
var staticRenderFns = ref.staticRenderFns;
var _parentVnode = ref._parentVnode;
if (staticRenderFns && !vm._staticTrees) {
2016-08-30 03:49:00 +08:00
vm._staticTrees = []
}
// set parent vnode. this allows render functions to have access
// to the data on the placeholder node.
2016-08-30 03:49:00 +08:00
vm.$vnode = _parentVnode
// render self
2016-08-30 03:49:00 +08:00
var vnode
try {
2016-08-30 03:49:00 +08:00
vnode = render.call(vm._renderProxy, vm.$createElement)
} catch (e) {
if (process.env.NODE_ENV !== 'production') {
2016-08-30 03:49:00 +08:00
warn(("Error when rendering " + (formatComponentName(vm)) + ":"))
}
/* istanbul ignore else */
if (config.errorHandler) {
2016-08-30 03:49:00 +08:00
config.errorHandler.call(null, e, vm)
} else {
if (config._isServer) {
2016-08-30 03:49:00 +08:00
throw e
} else {
2016-08-30 03:49:00 +08:00
setTimeout(function () { throw e }, 0)
}
}
// return previous vnode to prevent render error causing blank component
2016-08-30 03:49:00 +08:00
vnode = vm._vnode
}
// return empty vnode in case the render function errored out
if (!(vnode instanceof VNode)) {
if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) {
2016-08-30 03:49:00 +08:00
warn(
'Multiple root nodes returned from render function. Render function ' +
'should return a single root node.',
vm
)
}
2016-08-30 03:49:00 +08:00
vnode = emptyVNode()
}
// set parent
2016-08-30 03:49:00 +08:00
vnode.parent = _parentVnode
return vnode
}
// shorthands used in render functions
2016-08-30 03:49:00 +08:00
Vue.prototype._h = createElement
// toString for mustaches
2016-08-30 03:49:00 +08:00
Vue.prototype._s = _toString
// number conversion
2016-08-30 03:49:00 +08:00
Vue.prototype._n = toNumber
// empty vnode
Vue.prototype._e = emptyVNode
2016-07-27 12:25:41 +08:00
// render static tree by index
2016-08-30 03:49:00 +08:00
Vue.prototype._m = function renderStatic (
index,
isInFor
) {
var tree = this._staticTrees[index]
2016-08-10 12:55:30 +08:00
// if has already-rendered static tree and not inside v-for,
2016-08-30 03:49:00 +08:00
// we can reuse the same tree by doing a shallow clone.
2016-08-10 12:55:30 +08:00
if (tree && !isInFor) {
2016-08-30 03:49:00 +08:00
return Array.isArray(tree)
? cloneVNodes(tree)
: cloneVNode(tree)
2016-08-10 12:55:30 +08:00
}
// otherwise, render a fresh tree.
2016-08-30 03:49:00 +08:00
tree = this._staticTrees[index] = this.$options.staticRenderFns[index].call(this._renderProxy)
2016-08-10 12:55:30 +08:00
if (Array.isArray(tree)) {
for (var i = 0; i < tree.length; i++) {
2016-08-30 03:49:00 +08:00
tree[i].isStatic = true
tree[i].key = "__static__" + index + "_" + i
2016-08-10 12:55:30 +08:00
}
} else {
2016-08-30 03:49:00 +08:00
tree.isStatic = true
tree.key = "__static__" + index
2016-07-27 12:25:41 +08:00
}
2016-08-30 03:49:00 +08:00
return tree
}
// filter resolution helper
2016-08-30 03:49:00 +08:00
var identity = function (_) { return _; }
Vue.prototype._f = function resolveFilter (id) {
return resolveAsset(this.$options, 'filters', id, true) || identity
}
// render v-for
2016-08-30 03:49:00 +08:00
Vue.prototype._l = function renderList (
val,
render
) {
var ret, i, l, keys, key
if (Array.isArray(val)) {
2016-08-30 03:49:00 +08:00
ret = new Array(val.length)
for (i = 0, l = val.length; i < l; i++) {
2016-08-30 03:49:00 +08:00
ret[i] = render(val[i], i)
}
} else if (typeof val === 'number') {
2016-08-30 03:49:00 +08:00
ret = new Array(val)
for (i = 0; i < val; i++) {
2016-08-30 03:49:00 +08:00
ret[i] = render(i + 1, i)
}
} else if (isObject(val)) {
2016-08-30 03:49:00 +08:00
keys = Object.keys(val)
ret = new Array(keys.length)
for (i = 0, l = keys.length; i < l; i++) {
2016-08-30 03:49:00 +08:00
key = keys[i]
ret[i] = render(val[key], key, i)
}
}
2016-08-30 03:49:00 +08:00
return ret
}
2016-09-08 19:29:47 +08:00
// renderSlot
Vue.prototype._t = function (
name,
fallback
) {
var slotNodes = this.$slots[name]
if (slotNodes) {
// warn duplicate slot usage
if (process.env.NODE_ENV !== 'production') {
slotNodes._rendered && warn(
"Duplicate presense of slot \"" + name + "\" found in the same render tree " +
"- this will likely cause render errors.",
this
)
slotNodes._rendered = true
}
// clone slot nodes on re-renders
if (this._isMounted) {
slotNodes = cloneVNodes(slotNodes)
}
}
return slotNodes || fallback
}
// apply v-bind object
2016-08-30 03:49:00 +08:00
Vue.prototype._b = function bindProps (
vnode,
value,
asProp) {
if (value) {
if (!isObject(value)) {
2016-08-30 03:49:00 +08:00
process.env.NODE_ENV !== 'production' && warn(
'v-bind without argument expects an Object or Array value',
this
)
} else {
if (Array.isArray(value)) {
2016-08-30 03:49:00 +08:00
value = toObject(value)
}
2016-08-30 03:49:00 +08:00
var data = vnode.data
for (var key in value) {
if (key === 'class' || key === 'style') {
data[key] = value[key]
2016-08-06 06:14:22 +08:00
} else {
2016-08-30 03:49:00 +08:00
var hash = asProp || config.mustUseProp(key)
? data.domProps || (data.domProps = {})
: data.attrs || (data.attrs = {})
hash[key] = value[key]
2016-08-06 06:14:22 +08:00
}
}
}
}
2016-08-30 03:49:00 +08:00
}
// expose v-on keyCodes
2016-08-30 03:49:00 +08:00
Vue.prototype._k = function getKeyCodes (key) {
return config.keyCodes[key]
}
}
2016-08-30 03:49:00 +08:00
function resolveSlots (
renderChildren
) {
var slots = {}
if (!renderChildren) {
2016-08-30 03:49:00 +08:00
return slots
}
2016-08-30 03:49:00 +08:00
var children = normalizeChildren(renderChildren) || []
var defaultSlot = []
var name, child
for (var i = 0, l = children.length; i < l; i++) {
2016-08-30 03:49:00 +08:00
child = children[i]
if (child.data && (name = child.data.slot)) {
2016-08-30 03:49:00 +08:00
delete child.data.slot
var slot = (slots[name] || (slots[name] = []))
if (child.tag === 'template') {
2016-08-30 03:49:00 +08:00
slot.push.apply(slot, child.children)
} else {
2016-08-30 03:49:00 +08:00
slot.push(child)
}
} else {
2016-08-30 03:49:00 +08:00
defaultSlot.push(child)
}
}
// ignore single whitespace
2016-08-30 03:49:00 +08:00
if (defaultSlot.length && !(
defaultSlot.length === 1 &&
(defaultSlot[0].text === ' ' || defaultSlot[0].isComment)
)) {
slots.default = defaultSlot
}
2016-08-30 03:49:00 +08:00
return slots
}
2016-08-30 03:49:00 +08:00
/* */
function initEvents (vm) {
vm._events = Object.create(null)
// init parent attached events
2016-08-30 03:49:00 +08:00
var listeners = vm.$options._parentListeners
var on = bind(vm.$on, vm)
var off = bind(vm.$off, vm)
vm._updateListeners = function (listeners, oldListeners) {
2016-08-30 03:49:00 +08:00
updateListeners(listeners, oldListeners || {}, on, off)
}
if (listeners) {
2016-08-30 03:49:00 +08:00
vm._updateListeners(listeners)
}
}
2016-08-30 03:49:00 +08:00
function eventsMixin (Vue) {
Vue.prototype.$on = function (event, fn) {
2016-08-30 03:49:00 +08:00
var vm = this
;(vm._events[event] || (vm._events[event] = [])).push(fn)
return vm
}
Vue.prototype.$once = function (event, fn) {
2016-08-30 03:49:00 +08:00
var vm = this
function on () {
vm.$off(event, on)
fn.apply(vm, arguments)
}
2016-08-30 03:49:00 +08:00
on.fn = fn
vm.$on(event, on)
return vm
}
Vue.prototype.$off = function (event, fn) {
2016-08-30 03:49:00 +08:00
var vm = this
// all
if (!arguments.length) {
2016-08-30 03:49:00 +08:00
vm._events = Object.create(null)
return vm
}
// specific event
2016-08-30 03:49:00 +08:00
var cbs = vm._events[event]
if (!cbs) {
2016-08-30 03:49:00 +08:00
return vm
}
if (arguments.length === 1) {
2016-08-30 03:49:00 +08:00
vm._events[event] = null
return vm
}
// specific handler
2016-08-30 03:49:00 +08:00
var cb
var i = cbs.length
while (i--) {
2016-08-30 03:49:00 +08:00
cb = cbs[i]
if (cb === fn || cb.fn === fn) {
2016-08-30 03:49:00 +08:00
cbs.splice(i, 1)
break
}
}
2016-08-30 03:49:00 +08:00
return vm
}
Vue.prototype.$emit = function (event) {
2016-08-30 03:49:00 +08:00
var vm = this
var cbs = vm._events[event]
if (cbs) {
2016-08-30 03:49:00 +08:00
cbs = cbs.length > 1 ? toArray(cbs) : cbs
var args = toArray(arguments, 1)
for (var i = 0, l = cbs.length; i < l; i++) {
2016-08-30 03:49:00 +08:00
cbs[i].apply(vm, args)
}
}
2016-08-30 03:49:00 +08:00
return vm
}
}
2016-08-30 03:49:00 +08:00
/* */
var uid = 0
2016-08-30 03:49:00 +08:00
function initMixin (Vue) {
Vue.prototype._init = function (options) {
2016-08-30 03:49:00 +08:00
var vm = this
// a uid
2016-08-30 03:49:00 +08:00
vm._uid = uid++
// a flag to avoid this being observed
2016-08-30 03:49:00 +08:00
vm._isVue = true
// merge options
if (options && options._isComponent) {
// optimize internal component instantiation
// since dynamic options merging is pretty slow, and none of the
// internal component options needs special treatment.
2016-08-30 03:49:00 +08:00
initInternalComponent(vm, options)
} else {
2016-08-30 03:49:00 +08:00
vm.$options = mergeOptions(
resolveConstructorOptions(vm),
options || {},
vm
)
}
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
2016-08-30 03:49:00 +08:00
initProxy(vm)
} else {
2016-08-30 03:49:00 +08:00
vm._renderProxy = vm
}
// expose real self
2016-08-30 03:49:00 +08:00
vm._self = vm
initLifecycle(vm)
initEvents(vm)
callHook(vm, 'beforeCreate')
initState(vm)
callHook(vm, 'created')
initRender(vm)
}
function initInternalComponent (vm, options) {
var opts = vm.$options = Object.create(resolveConstructorOptions(vm))
// doing this because it's faster than dynamic enumeration.
2016-08-30 03:49:00 +08:00
opts.parent = options.parent
opts.propsData = options.propsData
opts._parentVnode = options._parentVnode
opts._parentListeners = options._parentListeners
opts._renderChildren = options._renderChildren
opts._componentTag = options._componentTag
if (options.render) {
2016-08-30 03:49:00 +08:00
opts.render = options.render
opts.staticRenderFns = options.staticRenderFns
}
}
2016-08-30 03:49:00 +08:00
function resolveConstructorOptions (vm) {
var Ctor = vm.constructor
var options = Ctor.options
if (Ctor.super) {
2016-08-30 03:49:00 +08:00
var superOptions = Ctor.super.options
var cachedSuperOptions = Ctor.superOptions
if (superOptions !== cachedSuperOptions) {
// super option changed
2016-08-30 03:49:00 +08:00
Ctor.superOptions = superOptions
options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions)
if (options.name) {
2016-08-30 03:49:00 +08:00
options.components[options.name] = Ctor
}
}
}
2016-08-30 03:49:00 +08:00
return options
}
}
2016-08-30 03:49:00 +08:00
function Vue (options) {
this._init(options)
}
2016-08-30 03:49:00 +08:00
initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)
/* */
/**
* Option overwriting strategies are functions that handle
* how to merge a parent option value and a child option
* value into the final value.
*/
2016-08-30 03:49:00 +08:00
var strats = config.optionMergeStrategies
/**
* Options with restrictions
*/
if (process.env.NODE_ENV !== 'production') {
strats.el = strats.propsData = function (parent, child, vm, key) {
if (!vm) {
2016-08-30 03:49:00 +08:00
warn(
"option \"" + key + "\" can only be used during instance " +
'creation with the `new` keyword.'
)
}
2016-08-30 03:49:00 +08:00
return defaultStrat(parent, child)
}
strats.name = function (parent, child, vm) {
2016-08-21 02:04:54 +08:00
if (vm && child) {
2016-08-30 03:49:00 +08:00
warn(
'options "name" can only be used as a component definition option, ' +
'not during instance creation.'
)
}
2016-08-30 03:49:00 +08:00
return defaultStrat(parent, child)
}
}
/**
* Helper that recursively merges two data objects together.
*/
2016-08-30 03:49:00 +08:00
function mergeData (to, from) {
var key, toVal, fromVal
for (key in from) {
2016-08-30 03:49:00 +08:00
toVal = to[key]
fromVal = from[key]
if (!hasOwn(to, key)) {
2016-08-30 03:49:00 +08:00
set(to, key, fromVal)
} else if (isObject(toVal) && isObject(fromVal)) {
2016-08-30 03:49:00 +08:00
mergeData(toVal, fromVal)
}
}
2016-08-30 03:49:00 +08:00
return to
}
/**
* Data
*/
2016-08-30 03:49:00 +08:00
strats.data = function (
parentVal,
childVal,
vm
) {
if (!vm) {
// in a Vue.extend merge, both should be functions
if (!childVal) {
2016-08-30 03:49:00 +08:00
return parentVal
}
if (typeof childVal !== 'function') {
2016-08-30 03:49:00 +08:00
process.env.NODE_ENV !== 'production' && warn(
'The "data" option should be a function ' +
'that returns a per-instance value in component ' +
'definitions.',
vm
)
return parentVal
}
if (!parentVal) {
2016-08-30 03:49:00 +08:00
return childVal
}
// when parentVal & childVal are both present,
// we need to return a function that returns the
// merged result of both functions... no need to
// check if parentVal is a function here because
// it has to be a function to pass previous merges.
2016-08-30 03:49:00 +08:00
return function mergedDataFn () {
return mergeData(
childVal.call(this),
parentVal.call(this)
)
}
} else if (parentVal || childVal) {
2016-08-30 03:49:00 +08:00
return function mergedInstanceDataFn () {
// instance merge
2016-08-30 03:49:00 +08:00
var instanceData = typeof childVal === 'function'
? childVal.call(vm)
: childVal
var defaultData = typeof parentVal === 'function'
? parentVal.call(vm)
: undefined
if (instanceData) {
2016-08-30 03:49:00 +08:00
return mergeData(instanceData, defaultData)
} else {
2016-08-30 03:49:00 +08:00
return defaultData
}
2016-08-30 03:49:00 +08:00
}
}
2016-08-30 03:49:00 +08:00
}
/**
* Hooks and param attributes are merged as arrays.
*/
2016-08-30 03:49:00 +08:00
function mergeHook (
parentVal,
childVal
) {
return childVal
? parentVal
? parentVal.concat(childVal)
: Array.isArray(childVal)
? childVal
: [childVal]
: parentVal
}
config._lifecycleHooks.forEach(function (hook) {
2016-08-30 03:49:00 +08:00
strats[hook] = mergeHook
})
/**
* Assets
*
* When a vm is present (instance creation), we need to do
* a three-way merge between constructor options, instance
* options and parent options.
*/
2016-08-30 03:49:00 +08:00
function mergeAssets (parentVal, childVal) {
var res = Object.create(parentVal || null)
return childVal
? extend(res, childVal)
: res
}
config._assetTypes.forEach(function (type) {
2016-08-30 03:49:00 +08:00
strats[type + 's'] = mergeAssets
})
/**
* Watchers.
*
* Watchers hashes should not overwrite one
* another, so we merge them as arrays.
*/
strats.watch = function (parentVal, childVal) {
/* istanbul ignore if */
2016-08-30 03:49:00 +08:00
if (!childVal) return parentVal
if (!parentVal) return childVal
var ret = {}
extend(ret, parentVal)
for (var key in childVal) {
2016-08-30 03:49:00 +08:00
var parent = ret[key]
var child = childVal[key]
if (parent && !Array.isArray(parent)) {
2016-08-30 03:49:00 +08:00
parent = [parent]
}
2016-08-30 03:49:00 +08:00
ret[key] = parent
? parent.concat(child)
: [child]
}
2016-08-30 03:49:00 +08:00
return ret
}
/**
* Other object hashes.
*/
2016-08-30 03:49:00 +08:00
strats.props =
strats.methods =
strats.computed = function (parentVal, childVal) {
if (!childVal) return parentVal
if (!parentVal) return childVal
var ret = Object.create(null)
extend(ret, parentVal)
extend(ret, childVal)
return ret
}
/**
* Default strategy.
*/
2016-08-30 03:49:00 +08:00
var defaultStrat = function (parentVal, childVal) {
return childVal === undefined
? parentVal
: childVal
}
/**
* Make sure component options get converted to actual
* constructors.
*/
2016-08-30 03:49:00 +08:00
function normalizeComponents (options) {
if (options.components) {
2016-08-30 03:49:00 +08:00
var components = options.components
var def
for (var key in components) {
2016-08-30 03:49:00 +08:00
var lower = key.toLowerCase()
if (isBuiltInTag(lower) || config.isReservedTag(lower)) {
2016-08-30 03:49:00 +08:00
process.env.NODE_ENV !== 'production' && warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + key
)
continue
}
2016-08-30 03:49:00 +08:00
def = components[key]
if (isPlainObject(def)) {
2016-08-30 03:49:00 +08:00
components[key] = Vue.extend(def)
}
}
}
}
/**
* Ensure all props option syntax are normalized into the
* Object-based format.
*/
2016-08-30 03:49:00 +08:00
function normalizeProps (options) {
var props = options.props
if (!props) return
var res = {}
var i, val, name
if (Array.isArray(props)) {
2016-08-30 03:49:00 +08:00
i = props.length
while (i--) {
2016-08-30 03:49:00 +08:00
val = props[i]
if (typeof val === 'string') {
2016-08-30 03:49:00 +08:00
name = camelize(val)
res[name] = { type: null }
} else if (process.env.NODE_ENV !== 'production') {
2016-08-30 03:49:00 +08:00
warn('props must be strings when using array syntax.')
}
}
} else if (isPlainObject(props)) {
for (var key in props) {
2016-08-30 03:49:00 +08:00
val = props[key]
name = camelize(key)
res[name] = isPlainObject(val)
? val
: { type: val }
}
}
2016-08-30 03:49:00 +08:00
options.props = res
}
/**
* Normalize raw function directives into object format.
*/
2016-08-30 03:49:00 +08:00
function normalizeDirectives (options) {
var dirs = options.directives
if (dirs) {
for (var key in dirs) {
2016-08-30 03:49:00 +08:00
var def = dirs[key]
if (typeof def === 'function') {
2016-08-30 03:49:00 +08:00
dirs[key] = { bind: def, update: def }
}
}
}
}
/**
* Merge two option objects into a new one.
* Core utility used in both instantiation and inheritance.
*/
2016-08-30 03:49:00 +08:00
function mergeOptions (
parent,
child,
vm
) {
normalizeComponents(child)
normalizeProps(child)
normalizeDirectives(child)
var extendsFrom = child.extends
if (extendsFrom) {
2016-08-30 03:49:00 +08:00
parent = typeof extendsFrom === 'function'
? mergeOptions(parent, extendsFrom.options, vm)
: mergeOptions(parent, extendsFrom, vm)
}
if (child.mixins) {
for (var i = 0, l = child.mixins.length; i < l; i++) {
2016-08-30 03:49:00 +08:00
var mixin = child.mixins[i]
if (mixin.prototype instanceof Vue) {
2016-08-30 03:49:00 +08:00
mixin = mixin.options
}
2016-08-30 03:49:00 +08:00
parent = mergeOptions(parent, mixin, vm)
}
}
2016-08-30 03:49:00 +08:00
var options = {}
var key
for (key in parent) {
2016-08-30 03:49:00 +08:00
mergeField(key)
}
for (key in child) {
if (!hasOwn(parent, key)) {
2016-08-30 03:49:00 +08:00
mergeField(key)
}
}
2016-08-30 03:49:00 +08:00
function mergeField (key) {
var strat = strats[key] || defaultStrat
options[key] = strat(parent[key], child[key], vm, key)
}
2016-08-30 03:49:00 +08:00
return options
}
/**
* Resolve an asset.
* This function is used because child instances need access
* to assets defined in its ancestor chain.
*/
2016-08-30 03:49:00 +08:00
function resolveAsset (
options,
type,
id,
warnMissing
) {
/* istanbul ignore if */
if (typeof id !== 'string') {
2016-08-30 03:49:00 +08:00
return
}
2016-08-30 03:49:00 +08:00
var assets = options[type]
var res = assets[id] ||
2016-08-30 03:49:00 +08:00
// camelCase ID
assets[camelize(id)] ||
// Pascal Case ID
assets[capitalize(camelize(id))]
if (process.env.NODE_ENV !== 'production' && warnMissing && !res) {
2016-08-30 03:49:00 +08:00
warn(
'Failed to resolve ' + type.slice(0, -1) + ': ' + id,
options
)
}
2016-08-30 03:49:00 +08:00
return res
}
2016-08-30 03:49:00 +08:00
/* */
function validateProp (
key,
propOptions,
propsData,
vm
) {
/* istanbul ignore if */
2016-08-30 03:49:00 +08:00
if (!propsData) return
var prop = propOptions[key]
var absent = !hasOwn(propsData, key)
var value = propsData[key]
// handle boolean props
2016-08-11 13:43:09 +08:00
if (getType(prop.type) === 'Boolean') {
if (absent && !hasOwn(prop, 'default')) {
2016-08-30 03:49:00 +08:00
value = false
} else if (value === '' || value === hyphenate(key)) {
2016-08-30 03:49:00 +08:00
value = true
}
}
// check default value
if (value === undefined) {
2016-08-30 03:49:00 +08:00
value = getPropDefaultValue(vm, prop, key)
// since the default value is a fresh copy,
// make sure to observe it.
2016-08-30 03:49:00 +08:00
var prevShouldConvert = observerState.shouldConvert
observerState.shouldConvert = true
observe(value)
observerState.shouldConvert = prevShouldConvert
}
if (process.env.NODE_ENV !== 'production') {
2016-08-30 03:49:00 +08:00
assertProp(prop, key, value, vm, absent)
}
2016-08-30 03:49:00 +08:00
return value
}
/**
* Get the default value of a prop.
*/
2016-08-30 03:49:00 +08:00
function getPropDefaultValue (vm, prop, name) {
// no default, return undefined
if (!hasOwn(prop, 'default')) {
2016-08-30 03:49:00 +08:00
return undefined
}
2016-08-30 03:49:00 +08:00
var def = prop.default
// warn against non-factory defaults for Object & Array
if (isObject(def)) {
2016-08-30 03:49:00 +08:00
process.env.NODE_ENV !== 'production' && warn(
'Invalid default value for prop "' + name + '": ' +
'Props with type Object/Array must use a factory function ' +
'to return the default value.',
vm
)
}
// call factory function for non-Function types
2016-08-30 03:49:00 +08:00
return typeof def === 'function' && prop.type !== Function
? def.call(vm)
: def
}
/**
* Assert whether a prop is valid.
*/
2016-08-30 03:49:00 +08:00
function assertProp (
prop,
name,
value,
vm,
absent
) {
if (prop.required && absent) {
2016-08-30 03:49:00 +08:00
warn(
'Missing required prop: "' + name + '"',
vm
)
return
}
if (value == null && !prop.required) {
2016-08-30 03:49:00 +08:00
return
}
2016-08-30 03:49:00 +08:00
var type = prop.type
var valid = !type
var expectedTypes = []
if (type) {
if (!Array.isArray(type)) {
2016-08-30 03:49:00 +08:00
type = [type]
}
for (var i = 0; i < type.length && !valid; i++) {
2016-08-30 03:49:00 +08:00
var assertedType = assertType(value, type[i])
expectedTypes.push(assertedType.expectedType)
valid = assertedType.valid
}
}
if (!valid) {
2016-08-30 03:49:00 +08:00
warn(
'Invalid prop: type check failed for prop "' + name + '".' +
' Expected ' + expectedTypes.map(capitalize).join(', ') +
', got ' + Object.prototype.toString.call(value).slice(8, -1) + '.',
vm
)
return
}
var validator = prop.validator
if (validator) {
if (!validator(value)) {
2016-08-30 03:49:00 +08:00
warn(
'Invalid prop: custom validator check failed for prop "' + name + '".',
vm
)
}
}
}
/**
* Assert the type of a value
*/
2016-08-30 03:49:00 +08:00
function assertType (value, type) {
var valid
var expectedType = getType(type)
2016-08-11 13:43:09 +08:00
if (expectedType === 'String') {
2016-08-30 03:49:00 +08:00
valid = typeof value === (expectedType = 'string')
2016-08-11 13:43:09 +08:00
} else if (expectedType === 'Number') {
2016-08-30 03:49:00 +08:00
valid = typeof value === (expectedType = 'number')
2016-08-11 13:43:09 +08:00
} else if (expectedType === 'Boolean') {
2016-08-30 03:49:00 +08:00
valid = typeof value === (expectedType = 'boolean')
2016-08-11 13:43:09 +08:00
} else if (expectedType === 'Function') {
2016-08-30 03:49:00 +08:00
valid = typeof value === (expectedType = 'function')
2016-08-11 13:43:09 +08:00
} else if (expectedType === 'Object') {
2016-08-30 03:49:00 +08:00
valid = isPlainObject(value)
2016-08-11 13:43:09 +08:00
} else if (expectedType === 'Array') {
2016-08-30 03:49:00 +08:00
valid = Array.isArray(value)
} else {
2016-08-30 03:49:00 +08:00
valid = value instanceof type
}
return {
valid: valid,
expectedType: expectedType
2016-08-30 03:49:00 +08:00
}
}
2016-08-11 13:43:09 +08:00
/**
* Use function string name to check built-in types,
* because a simple equality check will fail when running
* across different vms / iframes.
*/
2016-08-30 03:49:00 +08:00
function getType (fn) {
var match = fn && fn.toString().match(/^\s*function (\w+)/)
return match && match[1]
2016-08-11 13:43:09 +08:00
}
2016-08-30 03:49:00 +08:00
/* */
2016-08-30 03:49:00 +08:00
// attributes that should be using props for binding
var mustUseProp = makeMap('value,selected,checked,muted')
var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck')
var isBooleanAttr = makeMap(
'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' +
'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' +
'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' +
'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' +
'required,reversed,scoped,seamless,selected,sortable,translate,' +
'truespeed,typemustmatch,visible'
)
var isAttr = makeMap(
'accept,accept-charset,accesskey,action,align,alt,async,autocomplete,' +
'autofocus,autoplay,autosave,bgcolor,border,buffered,challenge,charset,' +
'checked,cite,class,code,codebase,color,cols,colspan,content,http-equiv,' +
'name,contenteditable,contextmenu,controls,coords,data,datetime,default,' +
'defer,dir,dirname,disabled,download,draggable,dropzone,enctype,method,for,' +
'form,formaction,headers,<th>,height,hidden,high,href,hreflang,http-equiv,' +
'icon,id,ismap,itemprop,keytype,kind,label,lang,language,list,loop,low,' +
'manifest,max,maxlength,media,method,GET,POST,min,multiple,email,file,' +
'muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,' +
'preload,radiogroup,readonly,rel,required,reversed,rows,rowspan,sandbox,' +
'scope,scoped,seamless,selected,shape,size,type,text,password,sizes,span,' +
'spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,' +
'target,title,type,usemap,value,width,wrap'
)
/* */
/* */
var isHTMLTag = makeMap(
'html,body,base,head,link,meta,style,title,' +
'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' +
'div,dd,dl,dt,figcaption,figure,hr,img,li,main,ol,p,pre,ul,' +
'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' +
's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' +
'embed,object,param,source,canvas,script,noscript,del,ins,' +
'caption,col,colgroup,table,thead,tbody,td,th,tr,' +
'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' +
'output,progress,select,textarea,' +
'details,dialog,menu,menuitem,summary,' +
'content,element,shadow,template'
)
var isUnaryTag = makeMap(
'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' +
'link,meta,param,source,track,wbr',
true
)
// Elements that you can, intentionally, leave open
// (and which close themselves)
2016-08-30 03:49:00 +08:00
var canBeLeftOpenTag = makeMap(
'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source',
true
)
// HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3
// Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content
2016-08-30 03:49:00 +08:00
var isNonPhrasingTag = makeMap(
'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' +
'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' +
'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' +
'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' +
'title,tr,track',
true
)
// this map is intentionally selective, only covering SVG elements that may
// contain child elements.
2016-08-30 03:49:00 +08:00
var isSVG = makeMap(
'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font,' +
'font-face,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' +
'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view',
true
)
2016-08-30 03:49:00 +08:00
var isPreTag = function (tag) { return tag === 'pre'; }
2016-08-02 03:31:12 +08:00
2016-08-30 03:49:00 +08:00
var isReservedTag = function (tag) {
return isHTMLTag(tag) || isSVG(tag)
}
2016-08-30 03:49:00 +08:00
function getTagNamespace (tag) {
if (isSVG(tag)) {
2016-08-30 03:49:00 +08:00
return 'svg'
}
// basic support for MathML
// note it doesn't support other MathML elements being component roots
if (tag === 'math') {
2016-08-30 03:49:00 +08:00
return 'math'
}
}
2016-08-30 03:49:00 +08:00
/* */
var UA = inBrowser && window.navigator.userAgent.toLowerCase()
var isIE = UA && /msie|trident/.test(UA)
var isIE9 = UA && UA.indexOf('msie 9.0') > 0
var isAndroid = UA && UA.indexOf('android') > 0
2016-08-10 12:55:30 +08:00
// According to
// https://w3c.github.io/DOM-Parsing/#dfn-serializing-an-attribute-value
// when serializing innerHTML, <, >, ", & should be encoded as entities.
// However, only some browsers, e.g. PhantomJS, encodes < and >.
// this causes problems with the in-browser parser.
2016-08-30 03:49:00 +08:00
var shouldDecodeTags = inBrowser ? (function () {
var div = document.createElement('div')
div.innerHTML = '<div a=">">'
return div.innerHTML.indexOf('&gt;') > 0
})() : false
/**
* Not type-checking this file because it's mostly vendor code.
*/
/*!
* HTML Parser By John Resig (ejohn.org)
* Modified by Juriy "kangax" Zaytsev
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*/
// Regular Expressions for parsing tags and attributes
2016-08-30 03:49:00 +08:00
var singleAttrIdentifier = /([^\s"'<>\/=]+)/
var singleAttrAssign = /(?:=)/
var singleAttrValues = [
2016-08-30 03:49:00 +08:00
// attr value double quotes
/"([^"]*)"+/.source,
// attr value, single quotes
/'([^']*)'+/.source,
// attr value, no quotes
/([^\s"'=<>`]+)/.source
]
var attribute = new RegExp(
'^\\s*' + singleAttrIdentifier.source +
'(?:\\s*(' + singleAttrAssign.source + ')' +
'\\s*(?:' + singleAttrValues.join('|') + '))?'
)
// could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName
// but for Vue templates we can enforce a simple charset
2016-08-30 03:49:00 +08:00
var ncname = '[a-zA-Z_][\\w\\-\\.]*'
var qnameCapture = '((?:' + ncname + '\\:)?' + ncname + ')'
var startTagOpen = new RegExp('^<' + qnameCapture)
var startTagClose = /^\s*(\/?)>/
var endTag = new RegExp('^<\\/' + qnameCapture + '[^>]*>')
var doctype = /^<!DOCTYPE [^>]+>/i
var IS_REGEX_CAPTURING_BROKEN = false
'x'.replace(/x(.)?/g, function (m, g) {
2016-08-30 03:49:00 +08:00
IS_REGEX_CAPTURING_BROKEN = g === ''
})
// Special Elements (can contain anything)
2016-08-30 03:49:00 +08:00
var isSpecialTag = makeMap('script,style', true)
2016-08-30 03:49:00 +08:00
var reCache = {}
2016-08-30 03:49:00 +08:00
var ampRE = /&amp;/g
var ltRE = /&lt;/g
var gtRE = /&gt;/g
var quoteRE = /&quot;/g
2016-07-27 12:25:41 +08:00
2016-08-30 03:49:00 +08:00
function decodeAttr (value, shouldDecodeTags) {
2016-07-27 12:25:41 +08:00
if (shouldDecodeTags) {
2016-08-30 03:49:00 +08:00
value = value.replace(ltRE, '<').replace(gtRE, '>')
2016-07-27 12:25:41 +08:00
}
2016-08-30 03:49:00 +08:00
return value.replace(ampRE, '&').replace(quoteRE, '"')
2016-07-27 12:25:41 +08:00
}
2016-08-30 03:49:00 +08:00
function parseHTML (html, options) {
var stack = []
var expectHTML = options.expectHTML
var isUnaryTag = options.isUnaryTag || no
var isFromDOM = options.isFromDOM
var shouldDecodeTags = options.shouldDecodeTags
var index = 0
var last, lastTag
while (html) {
2016-08-30 03:49:00 +08:00
last = html
// Make sure we're not in a script or style element
if (!lastTag || !isSpecialTag(lastTag)) {
2016-08-30 03:49:00 +08:00
var textEnd = html.indexOf('<')
if (textEnd === 0) {
// Comment:
if (/^<!--/.test(html)) {
2016-08-30 03:49:00 +08:00
var commentEnd = html.indexOf('-->')
if (commentEnd >= 0) {
2016-08-30 03:49:00 +08:00
advance(commentEnd + 3)
continue
}
}
// http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment
if (/^<!\[/.test(html)) {
2016-08-30 03:49:00 +08:00
var conditionalEnd = html.indexOf(']>')
if (conditionalEnd >= 0) {
2016-08-30 03:49:00 +08:00
advance(conditionalEnd + 2)
continue
}
}
// Doctype:
2016-08-30 03:49:00 +08:00
var doctypeMatch = html.match(doctype)
if (doctypeMatch) {
2016-08-30 03:49:00 +08:00
advance(doctypeMatch[0].length)
continue
}
// End tag:
2016-08-30 03:49:00 +08:00
var endTagMatch = html.match(endTag)
if (endTagMatch) {
2016-08-30 03:49:00 +08:00
var curIndex = index
advance(endTagMatch[0].length)
parseEndTag(endTagMatch[0], endTagMatch[1], curIndex, index)
continue
}
// Start tag:
2016-08-30 03:49:00 +08:00
var startTagMatch = parseStartTag()
if (startTagMatch) {
2016-08-30 03:49:00 +08:00
handleStartTag(startTagMatch)
continue
}
}
2016-08-30 03:49:00 +08:00
var text
if (textEnd >= 0) {
2016-08-30 03:49:00 +08:00
text = html.substring(0, textEnd)
advance(textEnd)
} else {
2016-08-30 03:49:00 +08:00
text = html
html = ''
}
if (options.chars) {
2016-08-30 03:49:00 +08:00
options.chars(text)
}
} else {
2016-08-30 03:49:00 +08:00
var stackedTag = lastTag.toLowerCase()
var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'))
var endTagLength = 0
2016-08-21 02:04:54 +08:00
var rest = html.replace(reStackedTag, function (all, text, endTag) {
2016-08-30 03:49:00 +08:00
endTagLength = endTag.length
2016-08-21 02:04:54 +08:00
if (stackedTag !== 'script' && stackedTag !== 'style' && stackedTag !== 'noscript') {
2016-08-30 03:49:00 +08:00
text = text
.replace(/<!--([\s\S]*?)-->/g, '$1')
.replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, '$1')
2016-08-21 02:04:54 +08:00
}
if (options.chars) {
2016-08-30 03:49:00 +08:00
options.chars(text)
2016-08-21 02:04:54 +08:00
}
2016-08-30 03:49:00 +08:00
return ''
})
index += html.length - rest.length
html = rest
parseEndTag('</' + stackedTag + '>', stackedTag, index - endTagLength, index)
}
if (html === last) {
2016-08-30 03:49:00 +08:00
throw new Error('Error parsing template:\n\n' + html)
}
}
// Clean up any remaining tags
2016-08-30 03:49:00 +08:00
parseEndTag()
2016-08-30 03:49:00 +08:00
function advance (n) {
index += n
html = html.substring(n)
}
2016-08-30 03:49:00 +08:00
function parseStartTag () {
var start = html.match(startTagOpen)
if (start) {
var match = {
tagName: start[1],
attrs: [],
start: index
2016-08-30 03:49:00 +08:00
}
advance(start[0].length)
var end, attr
while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) {
2016-08-30 03:49:00 +08:00
advance(attr[0].length)
match.attrs.push(attr)
}
if (end) {
2016-08-30 03:49:00 +08:00
match.unarySlash = end[1]
advance(end[0].length)
match.end = index
return match
}
}
}
2016-08-30 03:49:00 +08:00
function handleStartTag (match) {
var tagName = match.tagName
var unarySlash = match.unarySlash
if (expectHTML) {
if (lastTag === 'p' && isNonPhrasingTag(tagName)) {
2016-08-30 03:49:00 +08:00
parseEndTag('', lastTag)
}
if (canBeLeftOpenTag(tagName) && lastTag === tagName) {
2016-08-30 03:49:00 +08:00
parseEndTag('', tagName)
}
}
2016-08-30 03:49:00 +08:00
var unary = isUnaryTag(tagName) || tagName === 'html' && lastTag === 'head' || !!unarySlash
2016-08-30 03:49:00 +08:00
var l = match.attrs.length
var attrs = new Array(l)
for (var i = 0; i < l; i++) {
2016-08-30 03:49:00 +08:00
var args = match.attrs[i]
// hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778
if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) {
2016-08-30 03:49:00 +08:00
if (args[3] === '') { delete args[3] }
if (args[4] === '') { delete args[4] }
if (args[5] === '') { delete args[5] }
}
2016-08-30 03:49:00 +08:00
var value = args[3] || args[4] || args[5] || ''
attrs[i] = {
name: args[1],
2016-07-27 12:25:41 +08:00
value: isFromDOM ? decodeAttr(value, shouldDecodeTags) : value
2016-08-30 03:49:00 +08:00
}
}
if (!unary) {
2016-08-30 03:49:00 +08:00
stack.push({ tag: tagName, attrs: attrs })
lastTag = tagName
unarySlash = ''
}
if (options.start) {
2016-08-30 03:49:00 +08:00
options.start(tagName, attrs, unary, match.start, match.end)
}
}
2016-08-30 03:49:00 +08:00
function parseEndTag (tag, tagName, start, end) {
var pos
if (start == null) start = index
if (end == null) end = index
// Find the closest opened tag of the same type
if (tagName) {
2016-08-30 03:49:00 +08:00
var needle = tagName.toLowerCase()
for (pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos].tag.toLowerCase() === needle) {
2016-08-30 03:49:00 +08:00
break
}
}
} else {
// If no tag name is provided, clean shop
2016-08-30 03:49:00 +08:00
pos = 0
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (var i = stack.length - 1; i >= pos; i--) {
if (options.end) {
2016-08-30 03:49:00 +08:00
options.end(stack[i].tag, start, end)
}
}
// Remove the open elements from the stack
2016-08-30 03:49:00 +08:00
stack.length = pos
lastTag = pos && stack[pos - 1].tag
} else if (tagName.toLowerCase() === 'br') {
if (options.start) {
2016-08-30 03:49:00 +08:00
options.start(tagName, [], true, start, end)
}
} else if (tagName.toLowerCase() === 'p') {
if (options.start) {
2016-08-30 03:49:00 +08:00
options.start(tagName, [], false, start, end)
}
if (options.end) {
2016-08-30 03:49:00 +08:00
options.end(tagName, start, end)
}
}
}
}
2016-08-30 03:49:00 +08:00
/* */
function parseFilters (exp) {
var inSingle = false
var inDouble = false
var curly = 0
var square = 0
var paren = 0
var lastFilterIndex = 0
var c, prev, i, expression, filters
for (i = 0; i < exp.length; i++) {
2016-08-30 03:49:00 +08:00
prev = c
c = exp.charCodeAt(i)
if (inSingle) {
// check single quote
2016-08-30 03:49:00 +08:00
if (c === 0x27 && prev !== 0x5C) inSingle = !inSingle
} else if (inDouble) {
// check double quote
2016-08-30 03:49:00 +08:00
if (c === 0x22 && prev !== 0x5C) inDouble = !inDouble
} else if (
c === 0x7C && // pipe
exp.charCodeAt(i + 1) !== 0x7C &&
exp.charCodeAt(i - 1) !== 0x7C &&
!curly && !square && !paren
) {
if (expression === undefined) {
// first filter, end of expression
2016-08-30 03:49:00 +08:00
lastFilterIndex = i + 1
expression = exp.slice(0, i).trim()
} else {
2016-08-30 03:49:00 +08:00
pushFilter()
}
} else {
switch (c) {
2016-08-30 03:49:00 +08:00
case 0x22: inDouble = true; break // "
case 0x27: inSingle = true; break // '
case 0x28: paren++; break // (
case 0x29: paren--; break // )
case 0x5B: square++; break // [
case 0x5D: square--; break // ]
case 0x7B: curly++; break // {
case 0x7D: curly--; break // }
}
}
}
if (expression === undefined) {
2016-08-30 03:49:00 +08:00
expression = exp.slice(0, i).trim()
} else if (lastFilterIndex !== 0) {
2016-08-30 03:49:00 +08:00
pushFilter()
}
2016-08-30 03:49:00 +08:00
function pushFilter () {
(filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim())
lastFilterIndex = i + 1
}
if (filters) {
for (i = 0; i < filters.length; i++) {
2016-08-30 03:49:00 +08:00
expression = wrapFilter(expression, filters[i])
}
}
2016-08-30 03:49:00 +08:00
return expression
}
2016-08-30 03:49:00 +08:00
function wrapFilter (exp, filter) {
var i = filter.indexOf('(')
if (i < 0) {
// _f: resolveFilter
2016-08-30 03:49:00 +08:00
return ("_f(\"" + filter + "\")(" + exp + ")")
} else {
2016-08-30 03:49:00 +08:00
var name = filter.slice(0, i)
var args = filter.slice(i + 1)
return ("_f(\"" + name + "\")(" + exp + "," + args)
}
}
2016-08-30 03:49:00 +08:00
/* */
2016-08-30 03:49:00 +08:00
var defaultTagRE = /\{\{((?:.|\n)+?)\}\}/g
var regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g
2016-08-30 03:49:00 +08:00
var buildRegex = cached(function (delimiters) {
var open = delimiters[0].replace(regexEscapeRE, '\\$&')
var close = delimiters[1].replace(regexEscapeRE, '\\$&')
return new RegExp(open + '((?:.|\\n)+?)' + close, 'g')
})
function parseText (
text,
delimiters
) {
var tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE
if (!tagRE.test(text)) {
2016-08-30 03:49:00 +08:00
return
}
var tokens = []
var lastIndex = tagRE.lastIndex = 0
var match, index
while ((match = tagRE.exec(text))) {
index = match.index
// push text token
if (index > lastIndex) {
2016-08-30 03:49:00 +08:00
tokens.push(JSON.stringify(text.slice(lastIndex, index)))
}
// tag token
2016-08-30 03:49:00 +08:00
var exp = parseFilters(match[1].trim())
tokens.push(("_s(" + exp + ")"))
lastIndex = index + match[0].length
}
if (lastIndex < text.length) {
2016-08-30 03:49:00 +08:00
tokens.push(JSON.stringify(text.slice(lastIndex)))
}
2016-08-30 03:49:00 +08:00
return tokens.join('+')
}
2016-08-30 03:49:00 +08:00
/* */
function baseWarn (msg) {
console.error(("[Vue parser]: " + msg))
}
2016-08-30 03:49:00 +08:00
function pluckModuleFunction (
modules,
key
) {
return modules
? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; })
: []
}
2016-08-30 03:49:00 +08:00
function addProp (el, name, value) {
(el.props || (el.props = [])).push({ name: name, value: value })
}
2016-08-30 03:49:00 +08:00
function addAttr (el, name, value) {
(el.attrs || (el.attrs = [])).push({ name: name, value: value })
}
2016-08-30 03:49:00 +08:00
function addDirective (
el,
name,
value,
arg,
modifiers
) {
(el.directives || (el.directives = [])).push({ name: name, value: value, arg: arg, modifiers: modifiers })
}
2016-08-30 03:49:00 +08:00
function addHook (el, name, code) {
var hooks = el.hooks || (el.hooks = {})
var hook = hooks[name]
/* istanbul ignore if */
if (hook) {
2016-08-30 03:49:00 +08:00
hook.push(code)
} else {
2016-08-30 03:49:00 +08:00
hooks[name] = [code]
}
}
2016-08-30 03:49:00 +08:00
function addHandler (
el,
name,
value,
modifiers,
important
) {
// check capture modifier
if (modifiers && modifiers.capture) {
2016-08-30 03:49:00 +08:00
delete modifiers.capture
name = '!' + name // mark the event as captured
}
2016-08-30 03:49:00 +08:00
var events
if (modifiers && modifiers.native) {
2016-08-30 03:49:00 +08:00
delete modifiers.native
events = el.nativeEvents || (el.nativeEvents = {})
} else {
2016-08-30 03:49:00 +08:00
events = el.events || (el.events = {})
}
2016-08-30 03:49:00 +08:00
var newHandler = { value: value, modifiers: modifiers }
var handlers = events[name]
/* istanbul ignore if */
if (Array.isArray(handlers)) {
2016-08-30 03:49:00 +08:00
important ? handlers.unshift(newHandler) : handlers.push(newHandler)
} else if (handlers) {
2016-08-30 03:49:00 +08:00
events[name] = important ? [newHandler, handlers] : [handlers, newHandler]
} else {
2016-08-30 03:49:00 +08:00
events[name] = newHandler
}
}
2016-08-30 03:49:00 +08:00
function getBindingAttr (
el,
name,
getStatic
) {
var dynamicValue =
getAndRemoveAttr(el, ':' + name) ||
getAndRemoveAttr(el, 'v-bind:' + name)
if (dynamicValue != null) {
2016-08-30 03:49:00 +08:00
return dynamicValue
} else if (getStatic !== false) {
2016-08-30 03:49:00 +08:00
var staticValue = getAndRemoveAttr(el, name)
if (staticValue != null) {
2016-08-30 03:49:00 +08:00
return JSON.stringify(staticValue)
}
}
}
2016-08-30 03:49:00 +08:00
function getAndRemoveAttr (el, name) {
var val
if ((val = el.attrsMap[name]) != null) {
2016-08-30 03:49:00 +08:00
var list = el.attrsList
for (var i = 0, l = list.length; i < l; i++) {
if (list[i].name === name) {
2016-08-30 03:49:00 +08:00
list.splice(i, 1)
break
}
}
}
2016-08-30 03:49:00 +08:00
return val
}
2016-08-30 03:49:00 +08:00
/* */
var dirRE = /^v-|^@|^:/
var forAliasRE = /(.*)\s+(?:in|of)\s+(.*)/
var forIteratorRE = /\(([^,]*),([^,]*)(?:,([^,]*))?\)/
var bindRE = /^:|^v-bind:/
var onRE = /^@|^v-on:/
var argRE = /:(.*)$/
var modifierRE = /\.[^\.]+/g
2016-08-30 03:49:00 +08:00
var decodeHTMLCached = cached(entities.decodeHTML)
// configurable state
2016-08-30 03:49:00 +08:00
var warn$1
var platformGetTagNamespace
var platformMustUseProp
var platformIsPreTag
var preTransforms
var transforms
var postTransforms
var delimiters
/**
* Convert HTML string to AST.
*/
2016-08-30 03:49:00 +08:00
function parse (
template,
options
) {
warn$1 = options.warn || baseWarn
platformGetTagNamespace = options.getTagNamespace || no
platformMustUseProp = options.mustUseProp || no
platformIsPreTag = options.isPreTag || no
preTransforms = pluckModuleFunction(options.modules, 'preTransformNode')
transforms = pluckModuleFunction(options.modules, 'transformNode')
postTransforms = pluckModuleFunction(options.modules, 'postTransformNode')
delimiters = options.delimiters
var stack = []
var preserveWhitespace = options.preserveWhitespace !== false
var root
var currentParent
var inVPre = false
var inPre = false
var warned = false
parseHTML(template, {
expectHTML: options.expectHTML,
isUnaryTag: options.isUnaryTag,
2016-07-27 12:25:41 +08:00
isFromDOM: options.isFromDOM,
shouldDecodeTags: options.shouldDecodeTags,
2016-08-30 03:49:00 +08:00
start: function start (tag, attrs, unary) {
// check namespace.
// inherit parent ns if there is one
2016-08-30 03:49:00 +08:00
var ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag)
// handle IE svg bug
/* istanbul ignore if */
if (options.isIE && ns === 'svg') {
2016-08-30 03:49:00 +08:00
attrs = guardIESVGBug(attrs)
}
var element = {
type: 1,
tag: tag,
attrsList: attrs,
attrsMap: makeAttrsMap(attrs),
parent: currentParent,
children: []
2016-08-30 03:49:00 +08:00
}
if (ns) {
2016-08-30 03:49:00 +08:00
element.ns = ns
}
2016-08-16 11:39:07 +08:00
if (process.env.VUE_ENV !== 'server' && isForbiddenTag(element)) {
2016-08-30 03:49:00 +08:00
element.forbidden = true
process.env.NODE_ENV !== 'production' && warn$1(
'Templates should only be responsible for mapping the state to the ' +
'UI. Avoid placing tags with side-effects in your templates, such as ' +
"<" + tag + ">."
)
}
2016-07-27 12:25:41 +08:00
// apply pre-transforms
for (var i = 0; i < preTransforms.length; i++) {
2016-08-30 03:49:00 +08:00
preTransforms[i](element, options)
2016-07-27 12:25:41 +08:00
}
2016-08-02 03:31:12 +08:00
if (!inVPre) {
2016-08-30 03:49:00 +08:00
processPre(element)
if (element.pre) {
2016-08-30 03:49:00 +08:00
inVPre = true
}
}
2016-08-02 03:31:12 +08:00
if (platformIsPreTag(element.tag)) {
2016-08-30 03:49:00 +08:00
inPre = true
2016-08-02 03:31:12 +08:00
}
if (inVPre) {
2016-08-30 03:49:00 +08:00
processRawAttrs(element)
} else {
2016-08-30 03:49:00 +08:00
processFor(element)
processIf(element)
processOnce(element)
// determine whether this is a plain element after
// removing structural attributes
2016-08-30 03:49:00 +08:00
element.plain = !element.key && !attrs.length
processKey(element)
processRef(element)
processSlot(element)
processComponent(element)
for (var i$1 = 0; i$1 < transforms.length; i$1++) {
transforms[i$1](element, options)
}
2016-08-30 03:49:00 +08:00
processAttrs(element)
}
2016-08-30 03:49:00 +08:00
function checkRootConstraints (el) {
if (process.env.NODE_ENV !== 'production') {
2016-08-02 03:31:12 +08:00
if (el.tag === 'slot' || el.tag === 'template') {
2016-08-30 03:49:00 +08:00
warn$1(
"Cannot use <" + (el.tag) + "> as component root element because it may " +
'contain multiple nodes:\n' + template
)
}
2016-08-02 03:31:12 +08:00
if (el.attrsMap.hasOwnProperty('v-for')) {
2016-08-30 03:49:00 +08:00
warn$1(
'Cannot use v-for on stateful component root element because ' +
'it renders multiple elements:\n' + template
)
}
}
2016-08-02 03:31:12 +08:00
}
// tree management
if (!root) {
2016-08-30 03:49:00 +08:00
root = element
checkRootConstraints(root)
} else if (process.env.NODE_ENV !== 'production' && !stack.length && !warned) {
2016-08-02 03:31:12 +08:00
// allow 2 root elements with v-if and v-else
2016-08-30 03:49:00 +08:00
if ((root.attrsMap.hasOwnProperty('v-if') && element.attrsMap.hasOwnProperty('v-else'))) {
checkRootConstraints(element)
2016-08-02 03:31:12 +08:00
} else {
2016-08-30 03:49:00 +08:00
warned = true
warn$1(
("Component template should contain exactly one root element:\n\n" + template)
)
2016-08-02 03:31:12 +08:00
}
}
if (currentParent && !element.forbidden) {
if (element.else) {
2016-08-30 03:49:00 +08:00
processElse(element, currentParent)
} else {
2016-08-30 03:49:00 +08:00
currentParent.children.push(element)
element.parent = currentParent
}
}
if (!unary) {
2016-08-30 03:49:00 +08:00
currentParent = element
stack.push(element)
}
2016-07-27 12:25:41 +08:00
// apply post-transforms
2016-08-30 03:49:00 +08:00
for (var i$2 = 0; i$2 < postTransforms.length; i$2++) {
postTransforms[i$2](element, options)
2016-07-27 12:25:41 +08:00
}
},
2016-08-30 03:49:00 +08:00
end: function end () {
// remove trailing whitespace
2016-08-30 03:49:00 +08:00
var element = stack[stack.length - 1]
var lastNode = element.children[element.children.length - 1]
if (lastNode && lastNode.type === 3 && lastNode.text === ' ') {
2016-08-30 03:49:00 +08:00
element.children.pop()
}
// pop stack
2016-08-30 03:49:00 +08:00
stack.length -= 1
currentParent = stack[stack.length - 1]
// check pre state
if (element.pre) {
2016-08-30 03:49:00 +08:00
inVPre = false
2016-08-02 03:31:12 +08:00
}
if (platformIsPreTag(element.tag)) {
2016-08-30 03:49:00 +08:00
inPre = false
}
},
2016-08-30 03:49:00 +08:00
chars: function chars (text) {
if (!currentParent) {
if (process.env.NODE_ENV !== 'production' && !warned) {
2016-08-30 03:49:00 +08:00
warned = true
warn$1(
'Component template should contain exactly one root element:\n\n' + template
)
}
2016-08-30 03:49:00 +08:00
return
}
2016-08-30 03:49:00 +08:00
text = inPre || text.trim()
? decodeHTMLCached(text)
// only preserve whitespace if its not right after a starting tag
: preserveWhitespace && currentParent.children.length ? ' ' : ''
if (text) {
2016-08-30 03:49:00 +08:00
var expression
2016-08-02 03:31:12 +08:00
if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) {
currentParent.children.push({
type: 2,
expression: expression,
text: text
2016-08-30 03:49:00 +08:00
})
} else {
currentParent.children.push({
type: 3,
text: text
2016-08-30 03:49:00 +08:00
})
}
}
}
2016-08-30 03:49:00 +08:00
})
return root
}
2016-08-30 03:49:00 +08:00
function processPre (el) {
if (getAndRemoveAttr(el, 'v-pre') != null) {
2016-08-30 03:49:00 +08:00
el.pre = true
}
}
2016-08-30 03:49:00 +08:00
function processRawAttrs (el) {
var l = el.attrsList.length
if (l) {
2016-08-30 03:49:00 +08:00
var attrs = el.attrs = new Array(l)
for (var i = 0; i < l; i++) {
attrs[i] = {
name: el.attrsList[i].name,
value: JSON.stringify(el.attrsList[i].value)
2016-08-30 03:49:00 +08:00
}
}
} else if (!el.pre) {
// non root node in pre blocks with no attributes
2016-08-30 03:49:00 +08:00
el.plain = true
}
}
2016-08-30 03:49:00 +08:00
function processKey (el) {
var exp = getBindingAttr(el, 'key')
if (exp) {
2016-08-30 03:49:00 +08:00
el.key = exp
}
}
2016-08-30 03:49:00 +08:00
function processRef (el) {
var ref = getBindingAttr(el, 'ref')
if (ref) {
2016-08-30 03:49:00 +08:00
el.ref = ref
el.refInFor = checkInFor(el)
}
}
2016-08-30 03:49:00 +08:00
function processFor (el) {
var exp
if ((exp = getAndRemoveAttr(el, 'v-for'))) {
var inMatch = exp.match(forAliasRE)
if (!inMatch) {
2016-08-30 03:49:00 +08:00
process.env.NODE_ENV !== 'production' && warn$1(
("Invalid v-for expression: " + exp)
)
return
}
el.for = inMatch[2].trim()
var alias = inMatch[1].trim()
var iteratorMatch = alias.match(forIteratorRE)
if (iteratorMatch) {
2016-08-30 03:49:00 +08:00
el.alias = iteratorMatch[1].trim()
el.iterator1 = iteratorMatch[2].trim()
if (iteratorMatch[3]) {
2016-08-30 03:49:00 +08:00
el.iterator2 = iteratorMatch[3].trim()
}
} else {
2016-08-30 03:49:00 +08:00
el.alias = alias
}
}
}
2016-08-30 03:49:00 +08:00
function processIf (el) {
var exp = getAndRemoveAttr(el, 'v-if')
if (exp) {
2016-08-30 03:49:00 +08:00
el.if = exp
}
if (getAndRemoveAttr(el, 'v-else') != null) {
2016-08-30 03:49:00 +08:00
el.else = true
}
}
2016-08-30 03:49:00 +08:00
function processElse (el, parent) {
var prev = findPrevElement(parent.children)
if (prev && prev.if) {
2016-08-30 03:49:00 +08:00
prev.elseBlock = el
} else if (process.env.NODE_ENV !== 'production') {
2016-08-30 03:49:00 +08:00
warn$1(
("v-else used on element <" + (el.tag) + "> without corresponding v-if.")
)
}
}
2016-08-30 03:49:00 +08:00
function processOnce (el) {
var once = getAndRemoveAttr(el, 'v-once')
if (once != null) {
2016-08-30 03:49:00 +08:00
el.once = true
}
}
2016-08-30 03:49:00 +08:00
function processSlot (el) {
if (el.tag === 'slot') {
2016-08-30 03:49:00 +08:00
el.slotName = getBindingAttr(el, 'name')
} else {
2016-08-30 03:49:00 +08:00
var slotTarget = getBindingAttr(el, 'slot')
if (slotTarget) {
2016-08-30 03:49:00 +08:00
el.slotTarget = slotTarget
}
}
}
2016-08-30 03:49:00 +08:00
function processComponent (el) {
var binding
if ((binding = getBindingAttr(el, 'is'))) {
el.component = binding
}
if (getAndRemoveAttr(el, 'inline-template') != null) {
2016-08-30 03:49:00 +08:00
el.inlineTemplate = true
}
}
2016-08-30 03:49:00 +08:00
function processAttrs (el) {
var list = el.attrsList
var i, l, name, value, arg, modifiers, isProp
for (i = 0, l = list.length; i < l; i++) {
2016-08-30 03:49:00 +08:00
name = list[i].name
value = list[i].value
if (dirRE.test(name)) {
2016-08-02 03:31:12 +08:00
// mark element as dynamic
2016-08-30 03:49:00 +08:00
el.hasBindings = true
// modifiers
2016-08-30 03:49:00 +08:00
modifiers = parseModifiers(name)
if (modifiers) {
2016-08-30 03:49:00 +08:00
name = name.replace(modifierRE, '')
}
2016-08-30 03:49:00 +08:00
if (bindRE.test(name)) { // v-bind
name = name.replace(bindRE, '')
if (modifiers && modifiers.prop) {
2016-08-30 03:49:00 +08:00
isProp = true
name = camelize(name)
if (name === 'innerHtml') name = 'innerHTML'
}
if (isProp || platformMustUseProp(name)) {
2016-08-30 03:49:00 +08:00
addProp(el, name, value)
} else {
2016-08-30 03:49:00 +08:00
addAttr(el, name, value)
}
2016-08-30 03:49:00 +08:00
} else if (onRE.test(name)) { // v-on
name = name.replace(onRE, '')
addHandler(el, name, value, modifiers)
} else { // normal directives
name = name.replace(dirRE, '')
// parse arg
2016-08-30 03:49:00 +08:00
var argMatch = name.match(argRE)
if (argMatch && (arg = argMatch[1])) {
2016-08-30 03:49:00 +08:00
name = name.slice(0, -(arg.length + 1))
}
2016-08-30 03:49:00 +08:00
addDirective(el, name, value, arg, modifiers)
}
} else {
// literal attribute
if (process.env.NODE_ENV !== 'production') {
2016-08-30 03:49:00 +08:00
var expression = parseText(value, delimiters)
if (expression) {
2016-08-30 03:49:00 +08:00
warn$1(
name + "=\"" + value + "\": " +
'Interpolation inside attributes has been deprecated. ' +
'Use v-bind or the colon shorthand instead.'
)
}
}
2016-08-30 03:49:00 +08:00
addAttr(el, name, JSON.stringify(value))
}
}
}
2016-08-30 03:49:00 +08:00
function checkInFor (el) {
var parent = el
2016-08-16 11:39:07 +08:00
while (parent) {
if (parent.for !== undefined) {
2016-08-30 03:49:00 +08:00
return true
2016-08-16 11:39:07 +08:00
}
2016-08-30 03:49:00 +08:00
parent = parent.parent
2016-08-16 11:39:07 +08:00
}
2016-08-30 03:49:00 +08:00
return false
2016-08-16 11:39:07 +08:00
}
2016-08-30 03:49:00 +08:00
function parseModifiers (name) {
var match = name.match(modifierRE)
if (match) {
2016-08-30 03:49:00 +08:00
var ret = {}
match.forEach(function (m) { ret[m.slice(1)] = true })
return ret
}
}
2016-08-30 03:49:00 +08:00
function makeAttrsMap (attrs) {
var map = {}
for (var i = 0, l = attrs.length; i < l; i++) {
if (process.env.NODE_ENV !== 'production' && map[attrs[i].name]) {
2016-08-30 03:49:00 +08:00
warn$1('duplicate attribute: ' + attrs[i].name)
}
2016-08-30 03:49:00 +08:00
map[attrs[i].name] = attrs[i].value
}
2016-08-30 03:49:00 +08:00
return map
}
2016-08-30 03:49:00 +08:00
function findPrevElement (children) {
var i = children.length
while (i--) {
2016-08-30 03:49:00 +08:00
if (children[i].tag) return children[i]
}
}
2016-08-30 03:49:00 +08:00
function isForbiddenTag (el) {
return (
el.tag === 'style' ||
(el.tag === 'script' && (
!el.attrsMap.type ||
el.attrsMap.type === 'text/javascript'
))
)
}
2016-08-30 03:49:00 +08:00
var ieNSBug = /^xmlns:NS\d+/
var ieNSPrefix = /^NS\d+:/
/* istanbul ignore next */
2016-08-30 03:49:00 +08:00
function guardIESVGBug (attrs) {
var res = []
for (var i = 0; i < attrs.length; i++) {
2016-08-30 03:49:00 +08:00
var attr = attrs[i]
if (!ieNSBug.test(attr.name)) {
2016-08-30 03:49:00 +08:00
attr.name = attr.name.replace(ieNSPrefix, '')
res.push(attr)
}
}
2016-08-30 03:49:00 +08:00
return res
}
2016-08-30 03:49:00 +08:00
/* */
var isStaticKey
var isPlatformReservedTag
2016-08-30 03:49:00 +08:00
var genStaticKeysCached = cached(genStaticKeys$1)
/**
* Goal of the optimizier: walk the generated template AST tree
* and detect sub-trees that are purely static, i.e. parts of
* the DOM that never needs to change.
*
* Once we detect these sub-trees, we can:
*
* 1. Hoist them into constants, so that we no longer need to
* create fresh nodes for them on each re-render;
* 2. Completely skip them in the patching process.
*/
2016-08-30 03:49:00 +08:00
function optimize (root, options) {
if (!root) return
isStaticKey = genStaticKeysCached(options.staticKeys || '')
isPlatformReservedTag = options.isReservedTag || (function () { return false; })
// first pass: mark all non-static nodes.
2016-08-30 03:49:00 +08:00
markStatic(root)
// second pass: mark static roots.
2016-08-30 03:49:00 +08:00
markStaticRoots(root, false)
}
2016-08-30 03:49:00 +08:00
function genStaticKeys$1 (keys) {
return makeMap(
'type,tag,attrsList,attrsMap,plain,parent,children,attrs' +
(keys ? ',' + keys : '')
)
}
2016-08-30 03:49:00 +08:00
function markStatic (node) {
node.static = isStatic(node)
if (node.type === 1) {
for (var i = 0, l = node.children.length; i < l; i++) {
2016-08-30 03:49:00 +08:00
var child = node.children[i]
markStatic(child)
if (!child.static) {
2016-08-30 03:49:00 +08:00
node.static = false
}
}
}
}
2016-08-30 03:49:00 +08:00
function markStaticRoots (node, isInFor) {
2016-08-10 12:55:30 +08:00
if (node.type === 1) {
if (node.once || node.static) {
2016-08-30 03:49:00 +08:00
node.staticRoot = true
node.staticInFor = isInFor
return
2016-08-10 12:55:30 +08:00
}
if (node.children) {
for (var i = 0, l = node.children.length; i < l; i++) {
2016-08-30 03:49:00 +08:00
markStaticRoots(node.children[i], !!node.for)
2016-08-10 12:55:30 +08:00
}
}
}
}
2016-08-30 03:49:00 +08:00
function isStatic (node) {
if (node.type === 2) { // expression
return false
}
2016-08-30 03:49:00 +08:00
if (node.type === 3) { // text
return true
}
2016-08-30 03:49:00 +08:00
return !!(node.pre || (
!node.hasBindings && // no dynamic bindings
!node.if && !node.for && // not v-if or v-for or v-else
!isBuiltInTag(node.tag) && // not a built-in
isPlatformReservedTag(node.tag) && // not a component
Object.keys(node).every(isStaticKey)
))
}
2016-08-30 03:49:00 +08:00
/* */
var simplePathRE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?'\]|\[".*?"\]|\[\d+\]|\[[A-Za-z_$][\w$]*\])*$/
// keyCode aliases
var keyCodes = {
esc: 27,
tab: 9,
enter: 13,
space: 32,
up: 38,
left: 37,
right: 39,
down: 40,
'delete': [8, 46]
2016-08-30 03:49:00 +08:00
}
var modifierCode = {
stop: '$event.stopPropagation();',
prevent: '$event.preventDefault();',
self: 'if($event.target !== $event.currentTarget)return;'
2016-08-30 03:49:00 +08:00
}
2016-08-30 03:49:00 +08:00
function genHandlers (events, native) {
var res = native ? 'nativeOn:{' : 'on:{'
for (var name in events) {
2016-08-30 03:49:00 +08:00
res += "\"" + name + "\":" + (genHandler(events[name])) + ","
}
2016-08-30 03:49:00 +08:00
return res.slice(0, -1) + '}'
}
2016-08-30 03:49:00 +08:00
function genHandler (
handler
) {
if (!handler) {
2016-08-30 03:49:00 +08:00
return 'function(){}'
} else if (Array.isArray(handler)) {
2016-08-30 03:49:00 +08:00
return ("[" + (handler.map(genHandler).join(',')) + "]")
} else if (!handler.modifiers) {
2016-08-30 03:49:00 +08:00
return simplePathRE.test(handler.value)
? handler.value
: ("function($event){" + (handler.value) + "}")
} else {
2016-08-30 03:49:00 +08:00
var code = ''
var keys = []
for (var key in handler.modifiers) {
2016-08-21 02:04:54 +08:00
if (modifierCode[key]) {
2016-08-30 03:49:00 +08:00
code += modifierCode[key]
2016-08-21 02:04:54 +08:00
} else {
2016-08-30 03:49:00 +08:00
keys.push(key)
2016-08-21 02:04:54 +08:00
}
}
if (keys.length) {
2016-08-30 03:49:00 +08:00
code = genKeyFilter(keys) + code
}
2016-08-30 03:49:00 +08:00
var handlerCode = simplePathRE.test(handler.value)
? handler.value + '($event)'
: handler.value
return 'function($event){' + code + handlerCode + '}'
}
}
2016-08-30 03:49:00 +08:00
function genKeyFilter (keys) {
var code = keys.length === 1
? normalizeKeyCode(keys[0])
: Array.prototype.concat.apply([], keys.map(normalizeKeyCode))
if (Array.isArray(code)) {
2016-08-30 03:49:00 +08:00
return ("if(" + (code.map(function (c) { return ("$event.keyCode!==" + c); }).join('&&')) + ")return;")
} else {
2016-08-30 03:49:00 +08:00
return ("if($event.keyCode!==" + code + ")return;")
}
}
2016-08-30 03:49:00 +08:00
function normalizeKeyCode (key) {
return (
parseInt(key, 10) || // number keyCode
keyCodes[key] || // built-in alias
("_k(" + (JSON.stringify(key)) + ")") // custom alias
)
2016-08-21 02:04:54 +08:00
}
2016-08-30 03:49:00 +08:00
/* */
function bind$1 (el, dir) {
addHook(el, 'construct', ("_b(n1," + (dir.value) + (dir.modifiers && dir.modifiers.prop ? ',true' : '') + ")"))
}
var baseDirectives = {
bind: bind$1,
cloak: noop
2016-08-30 03:49:00 +08:00
}
/* */
// configurable state
2016-08-30 03:49:00 +08:00
var warn$2
var transforms$1
var dataGenFns
var platformDirectives
var staticRenderFns
var currentOptions
function generate (
ast,
options
) {
// save previous staticRenderFns so generate calls can be nested
2016-08-30 03:49:00 +08:00
var prevStaticRenderFns = staticRenderFns
var currentStaticRenderFns = staticRenderFns = []
currentOptions = options
warn$2 = options.warn || baseWarn
transforms$1 = pluckModuleFunction(options.modules, 'transformCode')
dataGenFns = pluckModuleFunction(options.modules, 'genData')
platformDirectives = options.directives || {}
var code = ast ? genElement(ast) : '_h("div")'
staticRenderFns = prevStaticRenderFns
return {
2016-08-30 03:49:00 +08:00
render: ("with(this){return " + code + "}"),
staticRenderFns: currentStaticRenderFns
2016-08-30 03:49:00 +08:00
}
}
2016-08-30 03:49:00 +08:00
function genElement (el) {
if (el.staticRoot && !el.staticProcessed) {
// hoist static sub-trees out
2016-08-30 03:49:00 +08:00
el.staticProcessed = true
staticRenderFns.push(("with(this){return " + (genElement(el)) + "}"))
return ("_m(" + (staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + ")")
} else if (el.for && !el.forProcessed) {
2016-08-30 03:49:00 +08:00
return genFor(el)
} else if (el.if && !el.ifProcessed) {
2016-08-30 03:49:00 +08:00
return genIf(el)
} else if (el.tag === 'template' && !el.slotTarget) {
2016-08-30 03:49:00 +08:00
return genChildren(el) || 'void 0'
} else if (el.tag === 'slot') {
2016-08-30 03:49:00 +08:00
return genSlot(el)
} else {
// component or element
2016-08-30 03:49:00 +08:00
var code
if (el.component) {
2016-08-30 03:49:00 +08:00
code = genComponent(el)
} else {
2016-08-30 03:49:00 +08:00
var data = genData(el)
var children = el.inlineTemplate ? null : genChildren(el)
code = "_h('" + (el.tag) + "'" + (data ? ("," + data) : '') + (children ? ("," + children) : '') + ")"
}
// module transforms
for (var i = 0; i < transforms$1.length; i++) {
2016-08-30 03:49:00 +08:00
code = transforms$1[i](el, code)
}
2016-08-30 03:49:00 +08:00
return code
}
}
2016-08-30 03:49:00 +08:00
function genIf (el) {
var exp = el.if
el.ifProcessed = true // avoid recursion
return ("(" + exp + ")?" + (genElement(el)) + ":" + (genElse(el)))
}
2016-08-30 03:49:00 +08:00
function genElse (el) {
return el.elseBlock
? genElement(el.elseBlock)
: '_e()'
}
2016-08-30 03:49:00 +08:00
function genFor (el) {
var exp = el.for
var alias = el.alias
var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : ''
var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : ''
el.forProcessed = true // avoid recursion
return "(" + exp + ")&&_l((" + exp + ")," +
"function(" + alias + iterator1 + iterator2 + "){" +
"return " + (genElement(el)) +
'})'
}
2016-08-30 03:49:00 +08:00
function genData (el) {
if (el.plain) {
2016-08-30 03:49:00 +08:00
return
}
2016-08-30 03:49:00 +08:00
var data = '{'
// directives first.
// directives may mutate the el's other properties before they are generated.
2016-08-30 03:49:00 +08:00
var dirs = genDirectives(el)
if (dirs) data += dirs + ','
// key
if (el.key) {
2016-08-30 03:49:00 +08:00
data += "key:" + (el.key) + ","
}
// ref
if (el.ref) {
2016-08-30 03:49:00 +08:00
data += "ref:" + (el.ref) + ","
}
if (el.refInFor) {
2016-08-30 03:49:00 +08:00
data += "refInFor:true,"
}
// record original tag name for components using "is" attribute
if (el.component) {
2016-08-30 03:49:00 +08:00
data += "tag:\"" + (el.tag) + "\","
}
// slot target
if (el.slotTarget) {
2016-08-30 03:49:00 +08:00
data += "slot:" + (el.slotTarget) + ","
}
// module data generation functions
for (var i = 0; i < dataGenFns.length; i++) {
2016-08-30 03:49:00 +08:00
data += dataGenFns[i](el)
}
// attributes
if (el.attrs) {
2016-08-30 03:49:00 +08:00
data += "attrs:{" + (genProps(el.attrs)) + "},"
}
// DOM props
if (el.props) {
2016-08-30 03:49:00 +08:00
data += "domProps:{" + (genProps(el.props)) + "},"
}
// hooks
if (el.hooks) {
2016-08-30 03:49:00 +08:00
data += "hook:{" + (genHooks(el.hooks)) + "},"
}
// event handlers
if (el.events) {
2016-08-30 03:49:00 +08:00
data += (genHandlers(el.events)) + ","
}
if (el.nativeEvents) {
2016-08-30 03:49:00 +08:00
data += (genHandlers(el.nativeEvents, true)) + ","
}
// inline-template
if (el.inlineTemplate) {
2016-08-30 03:49:00 +08:00
var ast = el.children[0]
if (process.env.NODE_ENV !== 'production' && (
el.children.length > 1 || ast.type !== 1
)) {
warn$2('Inline-template components must have exactly one child element.')
}
if (ast.type === 1) {
2016-08-30 03:49:00 +08:00
var inlineRenderFns = generate(ast, currentOptions)
data += "inlineTemplate:{render:function(){" + (inlineRenderFns.render) + "},staticRenderFns:[" + (inlineRenderFns.staticRenderFns.map(function (code) { return ("function(){" + code + "}"); }).join(',')) + "]}"
}
}
2016-08-30 03:49:00 +08:00
return data.replace(/,$/, '') + '}'
}
2016-08-30 03:49:00 +08:00
function genDirectives (el) {
var dirs = el.directives
if (!dirs) return
var res = 'directives:['
var hasRuntime = false
var i, l, dir, needRuntime
for (i = 0, l = dirs.length; i < l; i++) {
2016-08-30 03:49:00 +08:00
dir = dirs[i]
needRuntime = true
var gen = platformDirectives[dir.name] || baseDirectives[dir.name]
if (gen) {
// compile-time directive that manipulates AST.
// returns true if it also needs a runtime counterpart.
2016-08-30 03:49:00 +08:00
needRuntime = !!gen(el, dir, warn$2)
}
if (needRuntime) {
2016-08-30 03:49:00 +08:00
hasRuntime = true
res += "{name:\"" + (dir.name) + "\"" + (dir.value ? (",value:(" + (dir.value) + "),expression:" + (JSON.stringify(dir.value))) : '') + (dir.arg ? (",arg:\"" + (dir.arg) + "\"") : '') + (dir.modifiers ? (",modifiers:" + (JSON.stringify(dir.modifiers))) : '') + "},"
}
}
if (hasRuntime) {
2016-08-30 03:49:00 +08:00
return res.slice(0, -1) + ']'
}
}
2016-08-30 03:49:00 +08:00
function genChildren (el) {
2016-08-06 06:14:22 +08:00
if (el.children.length) {
2016-08-30 03:49:00 +08:00
return '[' + el.children.map(genNode).join(',') + ']'
}
}
2016-08-30 03:49:00 +08:00
function genNode (node) {
if (node.type === 1) {
2016-08-30 03:49:00 +08:00
return genElement(node)
} else {
2016-08-30 03:49:00 +08:00
return genText(node)
}
}
2016-08-30 03:49:00 +08:00
function genText (text) {
return text.type === 2
? text.expression // no need for () because already wrapped in _s()
: JSON.stringify(text.text)
}
2016-08-30 03:49:00 +08:00
function genSlot (el) {
2016-09-08 19:29:47 +08:00
var slotName = el.slotName || '"default"'
2016-08-30 03:49:00 +08:00
var children = genChildren(el)
return children
2016-09-08 19:29:47 +08:00
? ("_t(" + slotName + "," + children + ")")
: ("_t(" + slotName + ")")
}
2016-08-30 03:49:00 +08:00
function genComponent (el) {
var children = genChildren(el)
return ("_h(" + (el.component) + "," + (genData(el)) + (children ? ("," + children) : '') + ")")
}
2016-08-30 03:49:00 +08:00
function genProps (props) {
var res = ''
for (var i = 0; i < props.length; i++) {
2016-08-30 03:49:00 +08:00
var prop = props[i]
res += "\"" + (prop.name) + "\":" + (prop.value) + ","
}
2016-08-30 03:49:00 +08:00
return res.slice(0, -1)
}
2016-08-30 03:49:00 +08:00
function genHooks (hooks) {
var res = ''
for (var key in hooks) {
res += "\"" + key + "\":function(n1,n2){" + (hooks[key].join(';')) + "},"
}
2016-08-30 03:49:00 +08:00
return res.slice(0, -1)
}
2016-08-30 03:49:00 +08:00
/* */
/**
* Compile a template.
*/
2016-08-30 03:49:00 +08:00
function compile$2 (
template,
options
) {
var ast = parse(template.trim(), options)
optimize(ast, options)
var code = generate(ast, options)
return {
ast: ast,
render: code.render,
staticRenderFns: code.staticRenderFns
2016-08-30 03:49:00 +08:00
}
}
2016-08-30 03:49:00 +08:00
/* */
// operators like typeof, instanceof and in are allowed
2016-08-30 03:49:00 +08:00
var prohibitedKeywordRE = new RegExp('\\b' + (
'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
'super,throw,while,yield,delete,export,import,return,switch,default,' +
'extends,finally,continue,debugger,function,arguments'
).split(',').join('\\b|\\b') + '\\b')
// check valid identifier for v-for
2016-08-30 03:49:00 +08:00
var identRE = /[A-Za-z_$][\w$]*/
// strip strings in expressions
2016-08-30 03:49:00 +08:00
var stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g
// detect problematic expressions in a template
2016-08-30 03:49:00 +08:00
function detectErrors (ast) {
var errors = []
if (ast) {
2016-08-30 03:49:00 +08:00
checkNode(ast, errors)
}
2016-08-30 03:49:00 +08:00
return errors
}
2016-08-30 03:49:00 +08:00
function checkNode (node, errors) {
if (node.type === 1) {
for (var name in node.attrsMap) {
if (dirRE.test(name)) {
2016-08-30 03:49:00 +08:00
var value = node.attrsMap[name]
if (value) {
if (name === 'v-for') {
2016-08-30 03:49:00 +08:00
checkFor(node, ("v-for=\"" + value + "\""), errors)
} else {
2016-08-30 03:49:00 +08:00
checkExpression(value, (name + "=\"" + value + "\""), errors)
}
}
}
}
if (node.children) {
for (var i = 0; i < node.children.length; i++) {
2016-08-30 03:49:00 +08:00
checkNode(node.children[i], errors)
}
}
} else if (node.type === 2) {
2016-08-30 03:49:00 +08:00
checkExpression(node.expression, node.text, errors)
}
}
2016-08-30 03:49:00 +08:00
function checkFor (node, text, errors) {
checkExpression(node.for || '', text, errors)
checkIdentifier(node.alias, 'v-for alias', text, errors)
checkIdentifier(node.iterator1, 'v-for iterator', text, errors)
checkIdentifier(node.iterator2, 'v-for iterator', text, errors)
}
2016-08-30 03:49:00 +08:00
function checkIdentifier (ident, type, text, errors) {
if (typeof ident === 'string' && !identRE.test(ident)) {
2016-08-30 03:49:00 +08:00
errors.push(("- invalid " + type + " \"" + ident + "\" in expression: " + text))
}
}
2016-08-30 03:49:00 +08:00
function checkExpression (exp, text, errors) {
try {
2016-08-30 03:49:00 +08:00
new Function(("return " + exp))
} catch (e) {
2016-08-30 03:49:00 +08:00
var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE)
if (keywordMatch) {
2016-08-30 03:49:00 +08:00
errors.push(
"- avoid using JavaScript keyword as property name: " +
"\"" + (keywordMatch[0]) + "\" in expression " + text
)
} else {
2016-08-30 03:49:00 +08:00
errors.push(("- invalid expression: " + text))
}
}
}
2016-08-30 03:49:00 +08:00
/* */
function transformNode (el, options) {
var warn = options.warn || baseWarn
var staticClass = getAndRemoveAttr(el, 'class')
if (process.env.NODE_ENV !== 'production' && staticClass) {
2016-08-30 03:49:00 +08:00
var expression = parseText(staticClass, options.delimiters)
if (expression) {
2016-08-30 03:49:00 +08:00
warn(
"class=\"" + staticClass + "\": " +
'Interpolation inside attributes has been deprecated. ' +
'Use v-bind or the colon shorthand instead.'
)
}
}
2016-08-06 06:14:22 +08:00
if (staticClass) {
2016-08-30 03:49:00 +08:00
el.staticClass = JSON.stringify(staticClass)
2016-08-06 06:14:22 +08:00
}
2016-08-30 03:49:00 +08:00
var classBinding = getBindingAttr(el, 'class', false /* getStatic */)
if (classBinding) {
2016-08-30 03:49:00 +08:00
el.classBinding = classBinding
}
}
2016-08-30 03:49:00 +08:00
function genData$1 (el) {
var data = ''
if (el.staticClass) {
2016-08-30 03:49:00 +08:00
data += "staticClass:" + (el.staticClass) + ","
}
if (el.classBinding) {
2016-08-30 03:49:00 +08:00
data += "class:" + (el.classBinding) + ","
}
2016-08-30 03:49:00 +08:00
return data
}
var klass = {
staticKeys: ['staticClass'],
transformNode: transformNode,
genData: genData$1
2016-08-30 03:49:00 +08:00
}
2016-08-30 03:49:00 +08:00
/* */
function transformNode$1 (el) {
var styleBinding = getBindingAttr(el, 'style', false /* getStatic */)
if (styleBinding) {
2016-08-30 03:49:00 +08:00
el.styleBinding = styleBinding
}
}
2016-08-30 03:49:00 +08:00
function genData$2 (el) {
return el.styleBinding
? ("style:(" + (el.styleBinding) + "),")
: ''
}
var style = {
transformNode: transformNode$1,
genData: genData$2
}
2016-08-30 03:49:00 +08:00
var modules = [
klass,
style
]
2016-08-30 03:49:00 +08:00
/* */
2016-08-30 03:49:00 +08:00
var warn$3
function model (
el,
dir,
_warn
) {
warn$3 = _warn
var value = dir.value
var modifiers = dir.modifiers
var tag = el.tag
var type = el.attrsMap.type
if (tag === 'select') {
return genSelect(el, value)
} else if (tag === 'input' && type === 'checkbox') {
genCheckboxModel(el, value)
} else if (tag === 'input' && type === 'radio') {
genRadioModel(el, value)
} else {
return genDefaultModel(el, value, modifiers)
}
}
function genCheckboxModel (el, value) {
if (process.env.NODE_ENV !== 'production' &&
el.attrsMap.checked != null) {
warn$3(
"<" + (el.tag) + " v-model=\"" + value + "\" checked>:\n" +
"inline checked attributes will be ignored when using v-model. " +
'Declare initial values in the component\'s data option instead.'
)
}
var valueBinding = getBindingAttr(el, 'value') || 'null'
var trueValueBinding = getBindingAttr(el, 'true-value') || 'true'
var falseValueBinding = getBindingAttr(el, 'false-value') || 'false'
addProp(el, 'checked',
"Array.isArray(" + value + ")" +
"?(" + value + ").indexOf(" + valueBinding + ")>-1" +
":(" + value + ")===(" + trueValueBinding + ")"
)
addHandler(el, 'change',
"var $$a=" + value + "," +
'$$el=$event.target,' +
"$$c=$$el.checked?(" + trueValueBinding + "):(" + falseValueBinding + ");" +
'if(Array.isArray($$a)){' +
"var $$v=" + valueBinding + "," +
'$$i=$$a.indexOf($$v);' +
"if($$c){$$i<0&&(" + value + "=$$a.concat($$v))}" +
"else{$$i>-1&&(" + value + "=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}" +
"}else{" + value + "=$$c}",
null, true
)
}
function genRadioModel (el, value) {
if (process.env.NODE_ENV !== 'production' &&
el.attrsMap.checked != null) {
warn$3(
"<" + (el.tag) + " v-model=\"" + value + "\" checked>:\n" +
"inline checked attributes will be ignored when using v-model. " +
'Declare initial values in the component\'s data option instead.'
)
}
var valueBinding = getBindingAttr(el, 'value') || 'null'
addProp(el, 'checked', ("(" + value + ")===(" + valueBinding + ")"))
addHandler(el, 'change', (value + "=" + valueBinding), null, true)
}
function genDefaultModel (
el,
value,
modifiers
) {
if (process.env.NODE_ENV !== 'production') {
if (el.tag === 'input' && el.attrsMap.value) {
2016-08-30 03:49:00 +08:00
warn$3(
"<" + (el.tag) + " v-model=\"" + value + "\" value=\"" + (el.attrsMap.value) + "\">:\n" +
'inline value attributes will be ignored when using v-model. ' +
'Declare initial values in the component\'s data option instead.'
)
}
if (el.tag === 'textarea' && el.children.length) {
2016-08-30 03:49:00 +08:00
warn$3(
"<textarea v-model=\"" + value + "\">:\n" +
'inline content inside <textarea> will be ignored when using v-model. ' +
'Declare initial values in the component\'s data option instead.'
)
}
}
var type = el.attrsMap.type
var ref = modifiers || {};
var lazy = ref.lazy;
var number = ref.number;
var trim = ref.trim;
var event = lazy || (isIE && type === 'range') ? 'change' : 'input'
var needCompositionGuard = !lazy && type !== 'range'
var isNative = el.tag === 'input' || el.tag === 'textarea'
var valueExpression = isNative
? ("$event.target.value" + (trim ? '.trim()' : ''))
: "$event"
var code = number || type === 'number'
? (value + "=_n(" + valueExpression + ")")
: (value + "=" + valueExpression)
if (isNative && needCompositionGuard) {
2016-08-30 03:49:00 +08:00
code = "if($event.target.composing)return;" + code
}
2016-08-30 03:49:00 +08:00
addProp(el, 'value', isNative ? ("_s(" + value + ")") : ("(" + value + ")"))
addHandler(el, event, code, null, true)
if (needCompositionGuard) {
// need runtime directive code to help with composition events
2016-08-30 03:49:00 +08:00
return true
}
}
2016-08-30 03:49:00 +08:00
function genSelect (el, value) {
if (process.env.NODE_ENV !== 'production') {
2016-08-30 03:49:00 +08:00
el.children.some(checkOptionWarning)
}
2016-08-30 03:49:00 +08:00
var code = value + "=Array.prototype.filter" +
".call($event.target.options,function(o){return o.selected})" +
".map(function(o){return \"_value\" in o ? o._value : o.value})" +
(el.attrsMap.multiple == null ? '[0]' : '')
addHandler(el, 'change', code, null, true)
// need runtime to help with possible dynamically generated options
2016-08-30 03:49:00 +08:00
return true
}
2016-08-30 03:49:00 +08:00
function checkOptionWarning (option) {
if (option.type === 1 &&
option.tag === 'option' &&
option.attrsMap.selected != null) {
warn$3(
"<select v-model=\"" + (option.parent.attrsMap['v-model']) + "\">:\n" +
'inline selected attributes on <option> will be ignored when using v-model. ' +
'Declare initial values in the component\'s data option instead.'
)
return true
}
2016-08-30 03:49:00 +08:00
return false
}
2016-08-30 03:49:00 +08:00
/* */
function text (el, dir) {
if (dir.value) {
2016-08-30 03:49:00 +08:00
addProp(el, 'textContent', ("_s(" + (dir.value) + ")"))
}
}
2016-08-30 03:49:00 +08:00
/* */
function html (el, dir) {
if (dir.value) {
2016-08-30 03:49:00 +08:00
addProp(el, 'innerHTML', ("_s(" + (dir.value) + ")"))
}
}
var directives = {
model: model,
text: text,
html: html
2016-08-30 03:49:00 +08:00
}
2016-08-30 03:49:00 +08:00
/* */
var cache = Object.create(null)
var baseOptions = {
isIE: isIE,
expectHTML: true,
modules: modules,
staticKeys: genStaticKeys(modules),
directives: directives,
isReservedTag: isReservedTag,
isUnaryTag: isUnaryTag,
mustUseProp: mustUseProp,
2016-08-02 03:31:12 +08:00
getTagNamespace: getTagNamespace,
isPreTag: isPreTag
2016-08-30 03:49:00 +08:00
}
2016-08-30 03:49:00 +08:00
function compile$1 (
template,
options
) {
options = options
? extend(extend({}, baseOptions), options)
: baseOptions
return compile$2(template, options)
}
2016-08-30 03:49:00 +08:00
function compileToFunctions (
template,
options,
vm
) {
var _warn = (options && options.warn) || warn
// detect possible CSP restriction
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production') {
try {
2016-08-30 03:49:00 +08:00
new Function('return 1')
} catch (e) {
if (e.toString().match(/unsafe-eval|CSP/)) {
2016-08-30 03:49:00 +08:00
_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.'
)
}
}
}
2016-08-30 03:49:00 +08:00
var key = options && options.delimiters
? String(options.delimiters) + template
: template
if (cache[key]) {
2016-08-30 03:49:00 +08:00
return cache[key]
}
2016-08-30 03:49:00 +08:00
var res = {}
var compiled = compile$1(template, options)
res.render = makeFunction(compiled.render)
var l = compiled.staticRenderFns.length
res.staticRenderFns = new Array(l)
for (var i = 0; i < l; i++) {
2016-08-30 03:49:00 +08:00
res.staticRenderFns[i] = makeFunction(compiled.staticRenderFns[i])
}
if (process.env.NODE_ENV !== 'production') {
2016-08-30 03:49:00 +08:00
if (res.render === noop || res.staticRenderFns.some(function (fn) { return fn === noop; })) {
_warn(
"failed to compile template:\n\n" + template + "\n\n" +
detectErrors(compiled.ast).join('\n') +
'\n\n',
vm
)
}
}
2016-08-30 03:49:00 +08:00
return (cache[key] = res)
}
2016-08-30 03:49:00 +08:00
function makeFunction (code) {
try {
2016-08-30 03:49:00 +08:00
return new Function(code)
} catch (e) {
2016-08-30 03:49:00 +08:00
return noop
}
}
2016-08-30 03:49:00 +08:00
/* */
var splitRE = /\r?\n/g
var isSpecialTag$1 = makeMap('script,style,template', true)
/**
* Parse a single-file component (*.vue) file into an SFC Descriptor Object.
*/
2016-08-30 03:49:00 +08:00
function parseComponent (
content,
options
) {
if ( options === void 0 ) options = {};
var sfc = {
template: null,
script: null,
styles: []
2016-08-30 03:49:00 +08:00
}
var depth = 0
var currentBlock = null
2016-08-30 03:49:00 +08:00
function start (
tag,
attrs,
unary,
start,
end
) {
if (isSpecialTag$1(tag) && depth === 0) {
currentBlock = {
type: tag,
content: '',
start: end
2016-08-30 03:49:00 +08:00
}
checkAttrs(currentBlock, attrs)
if (tag === 'style') {
2016-08-30 03:49:00 +08:00
sfc.styles.push(currentBlock)
} else {
2016-08-30 03:49:00 +08:00
sfc[tag] = currentBlock
}
}
if (!unary) {
2016-08-30 03:49:00 +08:00
depth++
}
}
2016-08-30 03:49:00 +08:00
function checkAttrs (block, attrs) {
for (var i = 0; i < attrs.length; i++) {
2016-08-30 03:49:00 +08:00
var attr = attrs[i]
if (attr.name === 'lang') {
2016-08-30 03:49:00 +08:00
block.lang = attr.value
}
if (attr.name === 'scoped') {
2016-08-30 03:49:00 +08:00
block.scoped = true
}
if (attr.name === 'src') {
2016-08-30 03:49:00 +08:00
block.src = attr.value
}
}
}
2016-08-30 03:49:00 +08:00
function end (tag, start, end) {
if (isSpecialTag$1(tag) && depth === 1 && currentBlock) {
2016-08-30 03:49:00 +08:00
currentBlock.end = start
var 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) {
2016-08-30 03:49:00 +08:00
text = padContent(currentBlock) + text
}
2016-08-30 03:49:00 +08:00
currentBlock.content = text
currentBlock = null
}
2016-08-30 03:49:00 +08:00
depth--
}
2016-08-30 03:49:00 +08:00
function padContent (block) {
var offset = content.slice(0, block.start).split(splitRE).length
var padChar = block.type === 'script' && !block.lang
? '//\n'
: '\n'
return Array(offset).join(padChar)
}
parseHTML(content, {
start: start,
end: end
2016-08-30 03:49:00 +08:00
})
2016-08-30 03:49:00 +08:00
return sfc
}
2016-08-30 03:49:00 +08:00
/* */
function compile (
template,
options
) {
options = options || {}
var errors = []
// allow injecting modules/directives
2016-08-30 03:49:00 +08:00
var baseModules = baseOptions.modules || []
var modules = options.modules
? baseModules.concat(options.modules)
: baseModules
var directives = options.directives
? extend(extend({}, baseOptions.directives), options.directives)
: baseOptions.directives
var compiled = compile$1(template, {
modules: modules,
directives: directives,
2016-08-30 03:49:00 +08:00
warn: function (msg) {
errors.push(msg)
}
2016-08-30 03:49:00 +08:00
})
compiled.errors = errors.concat(detectErrors(compiled.ast))
return compiled
}
exports.compile = compile;
exports.parseComponent = parseComponent;
exports.compileToFunctions = compileToFunctions;