/* @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. 在python3下使用OpenCV 抓取摄像头图像提取蓝色

    工作中需要对摄像头进行调试, Python平台大大提高调试效率. 从网找到段代码, 可以从摄像头图像中抠出蓝色. import cv2 import numpy as np cap  = cv2.Vi ...

  2. Python3.x:BeautifulSoup()解析网页内容出现乱码

    Python3.x:BeautifulSoup()解析网页内容出现乱码 问题: start_html = requests.get(all_url, headers=Hostreferer) Beau ...

  3. asp.net发送短信

    public class SmsServiceManager { public static string Send(string PhoneNumber, out string sendNo) { ...

  4. hdu 2896:病毒侵袭

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission ...

  5. openwrt生成的镜像放在哪里

    答:1.打包好之后是放在build_dir/target-$(cross-compile-toolchan-name)/linux-$(chip-series-name)_$(chip-arch)/t ...

  6. maven问题:如何启动maven项目

    maven是项目构建工具,用于解决jar间的依赖,启动maven项目的命令:tomcat:run 步骤如下: 1.在pom.xml文件中配置插件,此处配置的是tomcat8 2.右击项目名,找到Run ...

  7. 探索C++虚函数

    探索C++虚函数 1 测试环境 各个编译器对虚函数的实现有各自区别,但原理大致相同.本文基于VS2008探索虚函数 2 测试代码 #pragma once #include <iostream& ...

  8. maven笔记(3)

    项目管理利器(Maven)——Pom.xml解析 <name>项目的描述名</name> <url>项目的地址</url> <descriptio ...

  9. angular之自定义 directive

    1,指令的创建至少需要一个带有@Directive装饰器修饰的控制器类.@Directive装饰器指定了一个选择器名称,用于指出与此指令相关联的属性的名字. 2,创建一个highlight.direc ...

  10. arm中的几个公式的比较

    串口 UART0.UBRDIVO=0X4d; 设置波特率 12000000/9600/16 -1=77化为16进制就是4dADC AD converter freq =50MHZ/(49+1) =1M ...