/* @flow */

import { hasOwn, isObject, isPlainObject, capitalize, hyphenate } from 'shared/util'
import { observe, observerState } from '../observer/index'
import { warn } from './debug' type PropOptions = {
type: Function | Array<Function> | null,
default: any,
required: ?boolean,
validator: ?Function
}; export function validateProp (
key: string,
propOptions: Object,
propsData: Object,
vm?: Component
): any {
const prop = propOptions[key] //如果 key不在 propsData中
const absent = !hasOwn(propsData, key)
let value = propsData[key]
// handle boolean props
//如果 传入的属性是 bool类型
if (isType(Boolean, prop.type)) {
if (absent && !hasOwn(prop, 'default')) {
value = false
} else if (!isType(String, prop.type) && (value === '' || value === hyphenate(key))) {
value = true
}
}
// check default value
if (value === undefined) {
value = getPropDefaultValue(vm, prop, key)
// since the default value is a fresh copy,
// make sure to observe it.
const prevShouldConvert = observerState.shouldConvert
observerState.shouldConvert = true
observe(value)
observerState.shouldConvert = prevShouldConvert
}
if (process.env.NODE_ENV !== 'production') {
assertProp(prop, key, value, vm, absent)
}
return value
} /**
* Get the default value of a prop.
*/
function getPropDefaultValue (vm: ?Component, prop: PropOptions, key: string): any {
// no default, return undefined
if (!hasOwn(prop, 'default')) {
return undefined
}
const def = prop.default
// warn against non-factory defaults for Object & Array
if (process.env.NODE_ENV !== 'production' && isObject(def)) {
warn(
'Invalid default value for prop "' + key + '": ' +
'Props with type Object/Array must use a factory function ' +
'to return the default value.',
vm
)
}
// the raw prop value was also undefined from previous render,
// return previous default value to avoid unnecessary watcher trigger
if (vm && vm.$options.propsData &&
vm.$options.propsData[key] === undefined &&
vm._props[key] !== undefined) {
return vm._props[key]
}
// call factory function for non-Function types
// a value is Function if its prototype is function even across different execution context
return typeof def === 'function' && getType(prop.type) !== 'Function'
? def.call(vm)
: def
} /**
* Assert whether a prop is valid.
*/
function assertProp (
prop: PropOptions,
name: string,
value: any,
vm: ?Component,
absent: boolean
) {
if (prop.required && absent) {
warn(
'Missing required prop: "' + name + '"',
vm
)
return
}
if (value == null && !prop.required) {
return
}
let type = prop.type
let valid = !type || type === true
const expectedTypes = []
if (type) {
if (!Array.isArray(type)) {
type = [type]
}
for (let i = 0; i < type.length && !valid; i++) {
const assertedType = assertType(value, type[i])
expectedTypes.push(assertedType.expectedType || '')
valid = assertedType.valid
}
}
if (!valid) {
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
}
const validator = prop.validator
if (validator) {
if (!validator(value)) {
warn(
'Invalid prop: custom validator check failed for prop "' + name + '".',
vm
)
}
}
} /**
* Assert the type of a value
*/
function assertType (value: any, type: Function): {
valid: boolean,
expectedType: ?string
} {
let valid
let expectedType = getType(type)
if (expectedType === 'String') {
valid = typeof value === (expectedType = 'string')
} else if (expectedType === 'Number') {
valid = typeof value === (expectedType = 'number')
} else if (expectedType === 'Boolean') {
valid = typeof value === (expectedType = 'boolean')
} else if (expectedType === 'Function') {
valid = typeof value === (expectedType = 'function')
} else if (expectedType === 'Object') {
valid = isPlainObject(value)
} else if (expectedType === 'Array') {
valid = Array.isArray(value)
} else {
valid = value instanceof type
}
return {
valid,
expectedType
}
} /**
* Use function string name to check built-in types,
* because a simple equality check will fail when running
* across different vms / iframes.

Number.toString()
    "function Number() { [native code] }"

  Boolean.toString()
"function Boolean() {[native code]}" toString 深入研究*/
function getType (fn) {
const match = fn && fn.toString().match(/^\s*function (\w+)/)
return match && match[1]
}

//如果传入的是数组, 只要数组中有一个是type, 就判断为相等, 因为如果type: [Boolean, Fuction, Number] 说明这个组件的属性满足其中一个即可
function isType (type, fn) {
if (!Array.isArray(fn)) {
return getType(fn) === getType(type)
}
for (let i = 0, len = fn.length; i < len; i++) {
if (getType(fn[i]) === getType(type)) {
return true
}
}
/* istanbul ignore next */
return false
}

vue.js 源代码学习笔记 ----- 工具方法 props的更多相关文章

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

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

  2. vue.js 源代码学习笔记 ----- 工具方法 option

    /* @flow */ import Vue from '../instance/index' import config from '../config' import { warn } from ...

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

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

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

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

  5. vue.js 源代码学习笔记 ----- 工具方法 perf

    import { inBrowser } from './env' export let mark export let measure if (process.env.NODE_ENV !== 'p ...

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

    import config from '../config' import { warn } from './debug' import { inBrowser } from './env' // 这 ...

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

    import config from '../config' import { noop } from 'shared/util' let warn = noop let tip = noop let ...

  8. vue.js 源代码学习笔记 ----- instance state

    /* @flow */ import Dep from '../observer/dep' import Watcher from '../observer/watcher' import { set ...

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

    参考 vue 2.2.6版本 /* @flow */ //引入订阅者模式 import Dep from './dep' import { arrayMethods } from './array' ...

随机推荐

  1. RESTful风格与RESTful Api

    REST(representational state transfer)(表述性状态转移),词汇解析: 1.representational 表述性:指资源以用各种形式来表述,包括 XML.JSON ...

  2. 20145313张雪纯 《Java程序设计》第7周学习总结

    20145313张雪纯 <Java程序设计>7周学习总结 教材学习内容总结 1967年定义的国际原子时,将秒的国际单位定义为铯原子辐射振动9192631170周耗费的时间. 为了简化日后对 ...

  3. JSON 中JsonConfig的使用(转)

    我们通常对一个Json串和Java对象进行互转时,经常会有选择性的过滤掉一些属性值,而json-lib包中的JsonConfig为我们提供了这种 功能,具体实现方法有以下几种.(1)建立JsonCon ...

  4. 爬虫bs4案例

    案例:使用BeautifuSoup4的爬虫 我们以腾讯社招页面来做演示:http://hr.tencent.com/position.php?&start=10#a 使用BeautifuSou ...

  5. AD 域中给AD 用加登录本地计算的权限

    说明:一般新添加的AD 用户没有登录计算机电脑的权限,如果需要添加登录权限. 步骤:1.打开Active Directory 用户和计算机 步骤:2.打开某个用户 步骤3; 如下图.

  6. Hdu 1455

    #include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> ...

  7. Python学习札记(十九) 高级特性5 迭代器

    参考:迭代器 Note 1.可用于for循环的对象有两类:(1)集合数据类型:list tuple dict str set (2)Generator:生成器和含yield语句的函数.这些可以直接作用 ...

  8. C++中的指针和数组

    最近看C++编程思想,看到第十三章动态内存管理的时候把自己给绕进去了,主要是在数据和指针这块弄混了.现在把找到的一些资料总结如下: 1. 数组是数组,指针是指针,两者并不等价: 2.数组在作为左值的时 ...

  9. webjars-jquery的引用

    什么是WebJars WebJars以jar包的形式来使用前端的各种框架.组件,如jquery.bootstrap WebJars将客户端(浏览器)资源(JavaScript,Css等)打成jar包文 ...

  10. 使用百度地图LBS创建自定义标注

    <body> <div id="allmap"></div> <div class="sel_container" i ...