vue.js 源代码学习笔记 ----- instance state
/* @flow */ import Dep from '../observer/dep'
import Watcher from '../observer/watcher' import {
set,
del,
observe,
observerState,
defineReactive
} from '../observer/index' import {
warn,
bind,
noop,
hasOwn,
isReserved,
handleError,
validateProp,
isPlainObject
} from '../util/index' const sharedPropertyDefinition = {
enumerable: true,
configurable: true,
get: noop,
set: noop
} export function proxy (target: Object, sourceKey: string, key: string) {
sharedPropertyDefinition.get = function proxyGetter () {
return this[sourceKey][key]
}
sharedPropertyDefinition.set = function proxySetter (val) {
this[sourceKey][key] = val
}
Object.defineProperty(target, key, sharedPropertyDefinition)
} export function initState (vm: Component) {
vm._watchers = []
const opts = vm.$options
if (opts.props) initProps(vm, opts.props)
if (opts.methods) initMethods(vm, opts.methods)
if (opts.data) {
initData(vm)
} else {
observe(vm._data = {}, true /* asRootData */)
}
if (opts.computed) initComputed(vm, opts.computed)
if (opts.watch) initWatch(vm, opts.watch)
} const isReservedProp = { key: 1, ref: 1, slot: 1 } function initProps (vm: Component, propsOptions: Object) {
const propsData = vm.$options.propsData || {}
const props = vm._props = {}
// cache prop keys so that future props updates can iterate using Array
// instead of dynamic object key enumeration.
const keys = vm.$options._propKeys = []
const isRoot = !vm.$parent
// root instance props should be converted
observerState.shouldConvert = isRoot
for (const key in propsOptions) {
keys.push(key)
const value = validateProp(key, propsOptions, propsData, vm)
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
if (isReservedProp[key]) {
warn(
`"${key}" is a reserved attribute and cannot be used as component prop.`,
vm
)
}
defineReactive(props, key, value, () => {
if (vm.$parent && !observerState.isSettingProps) {
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
)
}
})
} else {
defineReactive(props, key, value)
}
// static props are already proxied on the component's prototype
// during Vue.extend(). We only need to proxy props defined at
// instantiation here.
if (!(key in vm)) {
proxy(vm, `_props`, key)
}
}
observerState.shouldConvert = true
} function initData (vm: Component) {
let data = vm.$options.data
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {}
if (!isPlainObject(data)) {
data = {}
process.env.NODE_ENV !== 'production' && warn(
'data functions should return an object:\n' +
'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
vm
)
}
// proxy data on instance
const keys = Object.keys(data)
const props = vm.$options.props
let i = keys.length
while (i--) {
if (props && hasOwn(props, keys[i])) {
process.env.NODE_ENV !== 'production' && warn(
`The data property "${keys[i]}" is already declared as a prop. ` +
`Use prop default value instead.`,
vm
)
} else if (!isReserved(keys[i])) {
proxy(vm, `_data`, keys[i])
}
}
// observe data
observe(data, true /* asRootData */)
} function getData (data: Function, vm: Component): any {
try {
return data.call(vm)
} catch (e) {
handleError(e, vm, `data()`)
return {}
}
} const computedWatcherOptions = { lazy: true } function initComputed (vm: Component, computed: Object) {
const watchers = vm._computedWatchers = Object.create(null) for (const key in computed) {
const userDef = computed[key]
let getter = typeof userDef === 'function' ? userDef : userDef.get
if (process.env.NODE_ENV !== 'production') {
if (getter === undefined) {
warn(
`No getter function has been defined for computed property "${key}".`,
vm
)
getter = noop
}
}
// create internal watcher for the computed property.
watchers[key] = new Watcher(vm, getter, noop, computedWatcherOptions) // component-defined computed properties are already defined on the
// component prototype. We only need to define computed properties defined
// at instantiation here.
if (!(key in vm)) {
defineComputed(vm, key, userDef)
}
}
} export function defineComputed (target: any, key: string, userDef: Object | Function) {
if (typeof userDef === 'function') {
sharedPropertyDefinition.get = createComputedGetter(key)
sharedPropertyDefinition.set = noop
} else {
sharedPropertyDefinition.get = userDef.get
? userDef.cache !== false
? createComputedGetter(key)
: userDef.get
: noop
sharedPropertyDefinition.set = userDef.set
? userDef.set
: noop
}
Object.defineProperty(target, key, sharedPropertyDefinition)
} function createComputedGetter (key) {
return function computedGetter () {
const watcher = this._computedWatchers && this._computedWatchers[key]
if (watcher) {
if (watcher.dirty) {
watcher.evaluate()
}
if (Dep.target) {
watcher.depend()
}
return watcher.value
}
}
} function initMethods (vm: Component, methods: Object) {
const props = vm.$options.props
for (const key in methods) {
vm[key] = methods[key] == null ? noop : bind(methods[key], vm)
if (process.env.NODE_ENV !== 'production') {
if (methods[key] == null) {
warn(
`method "${key}" has an undefined value in the component definition. ` +
`Did you reference the function correctly?`,
vm
)
}
if (props && hasOwn(props, key)) {
warn(
`method "${key}" has already been defined as a prop.`,
vm
)
}
}
}
} function initWatch (vm: Component, watch: Object) {
for (const key in watch) {
const handler = watch[key]
if (Array.isArray(handler)) {
for (let i = 0; i < handler.length; i++) {
createWatcher(vm, key, handler[i])
}
} else {
createWatcher(vm, key, handler)
}
}
} function createWatcher (vm: Component, key: string, handler: any) {
let options
if (isPlainObject(handler)) {
options = handler
handler = handler.handler
}
if (typeof handler === 'string') {
handler = vm[handler]
}
vm.$watch(key, handler, options)
} export function stateMixin (Vue: Class<Component>) {
// flow somehow has problems with directly declared definition object
// when using Object.defineProperty, so we have to procedurally build up
// the object here.
const dataDef = {}
dataDef.get = function () { return this._data }
const propsDef = {}
propsDef.get = function () { return this._props }
if (process.env.NODE_ENV !== 'production') {
dataDef.set = function (newData: Object) {
warn(
'Avoid replacing instance root $data. ' +
'Use nested data properties instead.',
this
)
}
propsDef.set = function () {
warn(`$props is readonly.`, this)
}
}
Object.defineProperty(Vue.prototype, '$data', dataDef)
Object.defineProperty(Vue.prototype, '$props', propsDef) Vue.prototype.$set = set
Vue.prototype.$delete = del Vue.prototype.$watch = function (
expOrFn: string | Function,
cb: Function,
options?: Object
): Function {
const vm: Component = this
options = options || {}
options.user = true
const watcher = new Watcher(vm, expOrFn, cb, options)
if (options.immediate) {
cb.call(vm, watcher.value)
}
return function unwatchFn () {
watcher.teardown()
}
}
}
vue.js 源代码学习笔记 ----- instance state的更多相关文章
- vue.js 源代码学习笔记 ----- instance render
/* @flow */ import { warn, nextTick, toNumber, _toString, looseEqual, emptyObject, handleError, loos ...
- vue.js 源代码学习笔记 ----- instance init
/* @flow */ import config from '../config' import { initProxy } from './proxy' import { initState } ...
- vue.js 源代码学习笔记 ----- instance index
import { initMixin } from './init' import { stateMixin } from './state' import { renderMixin } from ...
- vue.js 源代码学习笔记 ----- instance event
/* @flow */ import { updateListeners } from '../vdom/helpers/index' import { toArray, tip, hyphenate ...
- vue.js 源代码学习笔记 ----- instance proxy
/* not type checking this file because flow doesn't play well with Proxy */ import config from 'core ...
- vue.js 源代码学习笔记 ----- instance inject
/* @flow */ import { hasSymbol } from 'core/util/env' import { warn } from '../util/index' import { ...
- vue.js 源代码学习笔记 ----- 工具方法 env
/* @flow */ /* globals MutationObserver */ import { noop } from 'shared/util' // can we use __proto_ ...
- vue.js 源代码学习笔记 ----- html-parse.js
/** * Not type-checking this file because it's mostly vendor code. */ /*! * HTML Parser By John Resi ...
- vue.js 源代码学习笔记 ----- core lifecycle
/* @flow */ import config from '../config' import Watcher from '../observer/watcher' import { mark, ...
随机推荐
- 337APuzzles
dangerous /*大水题目.不解释 给你m个数,从中选出n个,保证最大值和最小值的差值最小, 做法:从小到大排序,然后暴力枚举每个长度是n的序列*/ #include<stdio.h> ...
- Python面试题之Python反射机制
0x00 前言 def f1(): print('f1') def f2(): print('f2') def f3(): print('f3') def f4(): print('f4') a = ...
- Python学习笔记之Centos6.9安装Python3.6
0x00 注意 如果本机安装了python2,尽量不要管他,使用python3运行python脚本就好,因为可能有程序依赖目前的python2环境, 比如yum!!!!! 不要动现有的python2环 ...
- 20145216史婧瑶《Java程序设计》第一周学习总结
20145216 <Java程序设计>第1周学习总结 教材学习内容总结 第一章 Java平台概论 1.1 Java不只是语言 1.Java三大平台:Java SE.Java EE与Java ...
- Python for循环文件
for 循环遍历文件:打印文件的每一行 #!/usr/bin/env python fd = open('/tmp/hello.txt') for line in fd: print line, 注意 ...
- kali2016.2安装后配置
接触kali有几个月了,总是有一种浅尝辄止的感觉.因为不常用,一些常用操作时常想不起来了.为日后查找方便,特通过写博客方式来记录. 新建虚拟机,和安装其它操作系统差别不大,按提示一步一步安装.第1次安 ...
- Vue.js项目部署在Tomcat服务器上
1.在本地的Vue框架中 执行npm run build 将我们的项目打包到dist 文件夹中 2.在服务器上的Tomcat的 webapps文件夹下,新建一个文件夹如:frontvue 3.启动t ...
- 记jsp判断
empty:表示空字符串,null,空数组,空集合. ! empty:表示非空字符串,非null,非空数组,非空集合.
- elasticsearch系列(六)备份
快照备份 1.创建文件仓库 1.1 在$ELASTICSEARCH_HOME/config/elasticsearch.yaml中增加配置 #这个路径elasticsearch必须有权限访问,这个路径 ...
- Python学习札记(十九) 高级特性5 迭代器
参考:迭代器 Note 1.可用于for循环的对象有两类:(1)集合数据类型:list tuple dict str set (2)Generator:生成器和含yield语句的函数.这些可以直接作用 ...