props整体流程图

props整体流程图.png

props处理

我们把与props相关的逻辑主要分成三个部分,分别是props规范化、props初始化和props更新。
在日常的开发过程中,我们主要有如下几种撰写组件props的方式:
1. 数组形式:props可以写成一个数组,但数组中的key元素必须为string类型。

  1. export default {
  2. props: ['name', 'age']
  3. }
  1. 键值不为对象:此种方式常见于只需要定义key类型的props。
    1. export default {
    2. props: {
    3. name: String
    4. }
    5. }
  2. 规范格式:此种方式是Vue.js接受props最好的格式,对于一个有很高要求的组件来说,它通过会撰写很严格的props规则,这在各个开源UI框架中是最常见的。 ```javascript

export default { props: { name: { type: String, default: ‘’ }, age: { type: Number, default: 0, validator (value) { return value >= 0 && value <= 100 } } } }

  1. props的实现原理大体是:父组件提供数据,子组件通过props字段选择自己需要哪些内容,Vue.js内部通过子组件的props选项将需要的数据筛选出来之后添加到子组件的上下文中。
  2. <a name="mf1qA"></a>
  3. ## **props规范化**
  4. props规范化所做的事情,就是把各种不是规范格式的形式,规范化为规范格式,方便Vue.js在后续的过程中处理props。<br />那么我们就来分析Vue.js是如何对props规范化的。<br />props规范化的过程发生在this._init()方法中的mergeOptions合并配置中:
  5. ```javascript
  6. import { mergeOptions } from '../util/index'
  7. export function _init (Vue) {
  8. const vm = this
  9. vm.$options = mergeOptions(
  10. resolveConstructorOptions(vm.constructor),
  11. options || {},
  12. vm
  13. )
  14. }

其中mergeOptions()方法是定义在src/core/util/options.js文件中,它在其中有一段这样的方法调用:

  1. export function mergeOptions (
  2. parent: Object,
  3. child: Object,
  4. vm?: Component
  5. ): Object {
  6. // 省略代码
  7. normalizeProps(child, vm)
  8. return options
  9. }

规范化props的代码,主要集中在normalizeProps()方法中,详细分析normalizeProps()方法:

  1. /**
  2. * Ensure all props option syntax are normalized into the
  3. * Object-based format.
  4. */
  5. function normalizeProps (options: Object, vm: ?Component) {
  6. const props = options.props
  7. //首先判断是否有props属性,没有则退出
  8. if (!props) return
  9. //res保存规格化后的结果
  10. const res = {}
  11. let i, val, name
  12. /*
  13. * 检查props是否为一个数组
  14. * 如果不是则调用isPlainObject函数检查是否为对象类型
  15. * 如果都不是则在非生产环境下打印警告
  16. * */
  17. if (Array.isArray(props)) {
  18. /**
  19. * 如果props是数组,那么通过while语句循环数组中的每一项,判断props名称类型是否为string:
  20. * 如果不是,则在非生产环境下打印警告
  21. * 如果是,则调用camelize函数将props名称驼峰化,即可将a-b的名称转换成aB
  22. */
  23. i = props.length
  24. while (i--) {
  25. val = props[i]
  26. if (typeof val === 'string') {
  27. name = camelize(val)
  28. res[name] = { type: null }
  29. } else if (process.env.NODE_ENV !== 'production') {
  30. warn('props must be strings when using array syntax.')
  31. }
  32. }
  33. } else if (isPlainObject(props)) {
  34. /**
  35. * 如果props是对象,props对象中的值可以是一个基础的类型函数、也可能是一个数组提供多个可能的类型,还可能是一个对象类型的高级选项
  36. * 使用for...in语句遍历props对象
  37. */
  38. for (const key in props) {
  39. val = props[key]
  40. name = camelize(key)
  41. res[name] = isPlainObject(val)
  42. ? val
  43. : { type: val }
  44. }
  45. } else if (process.env.NODE_ENV !== 'production') {
  46. warn(
  47. `Invalid value for option "props": expected an Array or an Object, ` +
  48. `but got ${toRawType(props)}.`,
  49. vm
  50. )
  51. }
  52. options.props = res
  53. }

1.数组形式:当props是数组时,会首先倒序遍历这个数组,然后使用typeof来判断数组元素的类型。
如果不是string类型,则在开发环境下报错,如果是string类型,则先把key转化为驼峰形式,然后把这个key赋值到临时的res对象中,此时的键值固定为{ type: null }
将Array类型的props规格化成object类型。

  1. // 规范化前
  2. export default {
  3. props: ['age', 'nick-name']
  4. }
  5. // 规范化后
  6. export default {
  7. props: {
  8. age: {
  9. type: null
  10. },
  11. nickName: {
  12. type: null
  13. }
  14. }
  15. }

2.对象形式:

  1. // props对象中的值可以是一个基础的类型函数
  2. {
  3. propA: Number
  4. }
  5. // 也可能是一个数组,提供多个可能的类型
  6. {
  7. propB: [String,Number]
  8. }
  9. // 还可能是一个对象类型的高级选项
  10. {
  11. propC: {
  12. type: String,
  13. required: true
  14. }
  15. }

当为对象时会使用for-in遍历对象,紧接着和数组形式一样使用camelize来把key转成驼峰形式,然后使用isPlainObject()方法来判断是否为普通对象。
如果不是,则转成{ type: Type }对象形式,其中Type为定义key时的Type,如果是,则直接使用这个对象。

  1. // 规范化前
  2. export default {
  3. props: {
  4. name: String,
  5. age: Number
  6. }
  7. }
  8. // 规范化后
  9. export default {
  10. props: {
  11. name: {
  12. type: String
  13. },
  14. age: {
  15. type: Number
  16. }
  17. }
  18. }

3.既不是数组形式也不是对象形式:报错

  1. // 报错:Invalid value for option "props": expected an Array or an Object,but got String
  2. export default {
  3. props: 'name, age'
  4. }

props初始化

在了解了props规范化后,我们紧接着来了解一下props初始化的过程。
初始化props的内部原理是:通过规格化之后的props从其父组件传入的props数据中或从使用new创建实例时传入的propsData参数中,筛选出需要的数据保存在vm._props中,然后在vm上设置代理,实现通过vm.x访问vm._props.x的目的。
props初始化过程发生在this._init()方法中, 在initState时被处理:

  1. export function initState (vm) {
  2. // 省略代码
  3. const opts = vm.$options
  4. if (opts.props) initProps(vm, opts.props)
  5. }

初始化props的方法叫做initProps

在仔细阅读initProps()方法后,我们可以对initProps()方法进行总结,它主要做三件事情:props校验和求值、props响应式和props代理。

[1] props校验和求值

props校验和求值的功能写在validateProp中,它的代码如下:

  1. export function validateProp (
  2. key: string,
  3. propOptions: Object,
  4. propsData: Object,
  5. vm?: Component
  6. ): any {
  7. const prop = propOptions[key]
  8. const absent = !hasOwn(propsData, key)
  9. let value = propsData[key]
  10. // 1.处理布尔类型的props
  11. const booleanIndex = getTypeIndex(Boolean, prop.type)
  12. if (booleanIndex > -1) {
  13. if (absent && !hasOwn(prop, 'default')) {
  14. value = false
  15. } else if (value === '' || value === hyphenate(key)) {
  16. // only cast empty string / same name to boolean if
  17. // boolean has higher priority
  18. const stringIndex = getTypeIndex(String, prop.type)
  19. if (stringIndex < 0 || booleanIndex < stringIndex) {
  20. value = true
  21. }
  22. }
  23. }
  24. // 2.检查默认值
  25. if (value === undefined) {
  26. value = getPropDefaultValue(vm, prop, key)
  27. // 因为默认值是新的数据,所以需要将它转换成响应式的
  28. const prevShouldObserve = shouldObserve
  29. toggleObserving(true)
  30. observe(value)
  31. toggleObserving(prevShouldObserve)
  32. }
  33. if (
  34. process.env.NODE_ENV !== 'production' &&
  35. // skip validation for weex recycle-list child component props
  36. !(__WEEX__ && isObject(value) && ('@binding' in value))
  37. ) {
  38. // 3.props断言
  39. assertProp(prop, key, value, vm, absent)
  40. }
  41. return value
  42. }

validateProp函数接收如下4个参数:

  • key: propOptions中的属性名。
  • propOptions: 子组件用户设置的props选项。
  • propsData: 父组件或用户提供的props数据。
  • vm: Vue.js实例上下文,this的别名。

函数中先声明3个变量prop、absent 和 value:

  • 变量 prop 保存的内容是当前这个key的 prop 选项
  • 变量absent表示当前的key在用户提供的props选项中是否存在
  • 变量value表示使用当前这个key在用户提供的props选项中获取的数据

也就是说这3个变量分别保存当前这个key的prop选项、prop数据以及一个布尔值(用来判断prop数据是否存在)
1.处理Boolean类型prop的特殊情况
先来看几个props传递Boolean的例子:

  1. // Component A
  2. export default {
  3. props: {
  4. fixed: Boolean
  5. }
  6. }
  7. // Component B
  8. export default {
  9. props: {
  10. fixed: [Boolean, String]
  11. }
  12. }
  13. // Component C
  14. export default {
  15. props: {
  16. fixed: []
  17. }
  18. }

回到源码中处理Boolean类型getTypeIndex的地方,这个函数代码如下:

  1. function getTypeIndex (type, expectedTypes): number {
  2. if (!Array.isArray(expectedTypes)) {
  3. return isSameType(expectedTypes, type) ? 0 : -1
  4. }
  5. for (let i = 0, len = expectedTypes.length; i < len; i++) {
  6. if (isSameType(expectedTypes[i], type)) {
  7. return i
  8. }
  9. }
  10. return -1
  11. }
  • 以ComponentA组件为例,它的props不是一个数组但却是Boolean类型,因此返回索引0
  • 以ComponentB组件为例,它的props是一个数组,所以遍历这个数组,然后返回Boolean类型在数组中的索引 i
  • 以ComponentC组件为例,虽然它是一个数组,但数组中没有任何元素,因此返回索引-1

在拿到booleanIndex后,走到下面这段代码逻辑:

  1. const booleanIndex = getTypeIndex(Boolean, prop.type)
  2. if (booleanIndex > -1) {
  3. if (absent && !hasOwn(prop, 'default')) {
  4. value = false
  5. } else if (value === '' || value === hyphenate(key)) {
  6. // only cast empty string / same name to boolean if
  7. // boolean has higher priority
  8. const stringIndex = getTypeIndex(String, prop.type)
  9. if (stringIndex < 0 || booleanIndex < stringIndex) {
  10. value = true
  11. }
  12. }
  13. }

上面的代码表示:
在if 条件判断中 absent 代表虽然我们在子组件中定义了props,但是父组件并没有传递任何值,然后&条件又判断了子组件props有没有提供default默认值选项,如果没有,那么它的值只能为false。

  1. // 父组件未传递fixed
  2. export default {
  3. name: 'ParentComponent'
  4. template: `<child-component />`
  5. }
  6. // 子组件fixed值取false
  7. export default {
  8. name: 'ChildComponent',
  9. props: {
  10. fixed: Boolean
  11. }
  12. }

在else if 条件判断中我们判断了两种特殊的props传递方式:

  1. // Parent Component A
  2. export default {
  3. name: 'ParentComponentA',
  4. template: `<child-component fixed />`
  5. }
  6. // Parent Component B
  7. export default {
  8. name: 'ParentComponentB',
  9. template: `<child-component fixed="fixed" />`
  10. }

对于第一个种情况stringIndex为-1,booleanIndex为0,因此value的值为true。
对于第二种情况,则需要根据props的定义具体区分:

  1. // Child Component A
  2. export default {
  3. name: 'ChildComponentA'
  4. props: {
  5. fixed: [Boolean, String]
  6. }
  7. }
  8. // Child Component B
  9. export default {
  10. name: 'ChildComponentB',
  11. props: [String, Boolean]
  12. }
  • 对于ChildComponentA来说,由于stringIndex值为1,booleanIndex值为0,booleanIndex < stringIndex因此我们可以认为Boolean具有更高的优先级,此时value的值为true。
  • 对于ChildComponentB来说,由于stringIndex值为0,booleanIndex值为1,stringIndex < booleanIndex因此我们可以认为String具有更高的优先级,此时value的值不处理。

2.处理defalut默认数据
处理完Boolean类型后,我们来处理默认值,我们提到过的虽然子组件定义了props,但父组件没有传递的情况。

  1. //父组件未传递fixed
  2. export default {
  3. name: 'ParentComponent'
  4. template: `<child-component />`
  5. }
  6. // 子组件提供了default选项
  7. export default {
  8. name: 'ChildComponent',
  9. props: {
  10. fixed: {
  11. type: Boolean,
  12. default: false
  13. }
  14. }
  15. }

对于以上案例会走如下代码的逻辑:

  1. if (value === undefined) {
  2. value = getPropDefaultValue(vm, prop, key)
  3. }
  4. function getPropDefaultValue (vm: ?Component, prop: PropOptions, key: string): any {
  5. // no default, return undefined
  6. // 子组件有没有提供default默认值选项,没有则直接返回undefined。
  7. if (!hasOwn(prop, 'default')) {
  8. return undefined
  9. }
  10. const def = prop.default
  11. // warn against non-factory defaults for Object & Array
  12. // 随后判断了default如果是引用类型,则提示必须把default写成一个函数
  13. if (process.env.NODE_ENV !== 'production' && isObject(def)) {
  14. warn(
  15. 'Invalid default value for prop "' + key + '": ' +
  16. 'Props with type Object/Array must use a factory function ' +
  17. 'to return the default value.',
  18. vm
  19. )
  20. }
  21. // the raw prop value was also undefined from previous render,
  22. // return previous default value to avoid unnecessary watcher trigger
  23. if (vm && vm.$options.propsData &&
  24. vm.$options.propsData[key] === undefined &&
  25. vm._props[key] !== undefined
  26. ) {
  27. return vm._props[key]
  28. }
  29. // call factory function for non-Function types
  30. // a value is Function if its prototype is function even across different execution context
  31. // 最后再根据default的类型来取值,如果是函数类型则调用这个函数,如果不是函数类型则直接使用。
  32. return typeof def === 'function' && getType(prop.type) !== 'Function'
  33. ? def.call(vm)
  34. : def
  35. }

代码分析:

  • 首先判断了子组件有没有提供default默认值选项,没有则直接返回undefined。
  • 随后判断了default如果是引用类型,则提示必须把default写成一个函数: ```javascript default: {} default: []

// 必须写成 default () { return {} } default () { return [] }

  1. ![image2020-11-26_15-4-40.png](https://cdn.nlark.com/yuque/0/2021/png/12436525/1634701167153-d0edc4b0-e937-4b0a-bb2b-5765a35ce868.png#clientId=u91776ad7-6f06-4&from=drop&id=ua4fe6f5f&margin=%5Bobject%20Object%5D&name=image2020-11-26_15-4-40.png&originHeight=202&originWidth=440&originalType=binary&ratio=1&size=11924&status=done&style=none&taskId=u761e5465-a367-4b41-82f7-e7dd930e8cb)
  2. - 最后再根据default的类型来取值,如果是函数类型则调用这个函数,如果不是函数类型则直接使用。
  3. **3.props 断言**<br />最后我们来分析一下props断言。
  4. ```javascript
  5. function assertProp (
  6. prop: PropOptions,
  7. name: string,
  8. value: any,
  9. vm: ?Component,
  10. absent: boolean
  11. ) {
  12. if (prop.required && absent) {
  13. warn(
  14. 'Missing required prop: "' + name + '"',
  15. vm
  16. )
  17. return
  18. }
  19. if (value == null && !prop.required) {
  20. return
  21. }
  22. let type = prop.type
  23. let valid = !type || type === true
  24. const expectedTypes = []
  25. if (type) {
  26. if (!Array.isArray(type)) {
  27. type = [type]
  28. }
  29. for (let i = 0; i < type.length && !valid; i++) {
  30. const assertedType = assertType(value, type[i])
  31. expectedTypes.push(assertedType.expectedType || '')
  32. valid = assertedType.valid
  33. }
  34. }
  35. if (!valid) {
  36. warn(
  37. getInvalidTypeMessage(name, value, expectedTypes),
  38. vm
  39. )
  40. return
  41. }
  42. const validator = prop.validator
  43. if (validator) {
  44. if (!validator(value)) {
  45. warn(
  46. 'Invalid prop: custom validator check failed for prop "' + name + '".',
  47. vm
  48. )
  49. }
  50. }
  51. }

在assertProp中我们有三种情况需要去断言:

  • required:如果子组件props提供了required选项,代表这个props必须在父组件中传递值,如果不传递则抛出错误信息Missing required prop: fixed。
  • 对于定义了多个type的类型数组,则我们会遍历这个类型数组,只要当前props的类型和类型数组中某一个元素匹配则终止遍历。,否则抛出错误提示信息。 ``javascript // Parent Component export default { name: 'ParentComponent', template:` } // Chil Component export default { name: ‘ChilComponent’, props: { age: [Number, String] } }

// 报错:Invalid prop: type check failed for prop age,Expected Number, String,got with value true

  1. - 用户自己提供的validator校验器我们也需要进行断言:
  2. ```javascript
  3. // Parent Component
  4. export default {
  5. name: 'ParentComponent',
  6. template: `<child-component :age="101" />`
  7. }
  8. // Chil Component
  9. export default {
  10. name: 'ChilComponent',
  11. props: {
  12. age: {
  13. type: Number,
  14. validator (value) {
  15. return value >=0 && value <=100
  16. }
  17. }
  18. }
  19. }
  20. // 报错:Invalid prop: custom validator check failed for prop age

[2] props响应式

这部分的过程主要使用了defineReactive方法,后面会详细介绍:

  1. if (process.env.NODE_ENV !== 'production') {
  2. const hyphenatedKey = hyphenate(key)
  3. if (isReservedAttribute(hyphenatedKey) ||
  4. config.isReservedAttr(hyphenatedKey)) {
  5. warn(
  6. `"${hyphenatedKey}" is a reserved attribute and cannot be used as component prop.`,
  7. vm
  8. )
  9. }
  10. defineReactive(props, key, value, () => {
  11. if (!isRoot && !isUpdatingChildComponent) {
  12. warn(
  13. `Avoid mutating a prop directly since the value will be ` +
  14. `overwritten whenever the parent component re-renders. ` +
  15. `Instead, use a data or computed property based on the prop's ` +
  16. `value. Prop being mutated: "${key}"`,
  17. vm
  18. )
  19. }
  20. })
  21. } else {
  22. // 调用validateProp函数将得到的props数据通过defineReactive函数设置到vm._props中
  23. defineReactive(props, key, value)
  24. }

值得注意的地方就是:在开发环境下,props的响应式劫持了setter方法,这样做的是为了保证props为单项数据流:即我们不能在子组件中直接修改父组件传递的props值。**

[3] props代理

经过props响应式后,我们会在实例上得到this._props对象,为了方便我们更好的获取props的值,我们需要对props做一层proxy代理。关于proxy的实现,我们后面会做介绍。

  1. this._props = {
  2. name: '',
  3. age: 0
  4. }
  5. // 代理前
  6. console.log(this._props.name)
  7. proxy(vm, `_props`, key)
  8. // 代理后
  9. console.log(this.name)

props更新

子组件的props值来源于父组件,当父组件值更新时,子组件的值也会发生改变,同时触发子组件的重新渲染。
先跳过父组件的具体编译逻辑,直接看父组件的值更新,改变子组件props值的步骤:

  1. // src/core/instance/lifecycle.js/updateChildComponent
  2. export function updateChildComponent (
  3. vm: Component,
  4. propsData: ?Object,
  5. listeners: ?Object,
  6. parentVnode: MountedComponentVNode,
  7. renderChildren: ?Array<VNode>
  8. ) {
  9. // 省略代码
  10. // update props
  11. if (propsData && vm.$options.props) {
  12. toggleObserving(false)
  13. const props = vm._props
  14. const propKeys = vm.$options._propKeys || []
  15. for (let i = 0; i < propKeys.length; i++) {
  16. const key = propKeys[i]
  17. const propOptions: any = vm.$options.props // wtf flow?
  18. props[key] = validateProp(key, propOptions, propsData, vm)
  19. }
  20. toggleObserving(true)
  21. // keep a copy of raw propsData
  22. vm.$options.propsData = propsData
  23. }
  24. }

代码分析:

  • 以上vm实例为子组件,propsData为父组件中传递的props的值,而_propKeys是之前props初始化过程中缓存起来的所有的props的key。
  • 在父组件值更新后,会通过遍历propsKey来重新对子组件props进行校验求值,最后赋值。

以上代码就是子组件props更新的过程,在props更新后会进行子组件的重新渲染,这个重新渲染的过程分两种情况:

  • 普通props值被修改:当props值被修改后,其中有段代码props[key] = validateProp(key, propOptions, propsData, vm)根据响应式原理,会触发属性的setter,进而子组件可以重新渲染。
  • 对象props内部属性变化:当这种情况发生时,并没有触发子组件prop的更新,但是在子组件渲染的时候读取到了props,因此会收集到这个props的render watcher,当对象props内部属性变化的时候,根据响应式原理依然会触发setter,进而子组件可以重新进行渲染。

    toggleObserving作用

    toggleObserving是定义在src/core/observer/index.js文件中的一个函数:
    1. export let shouldObserve: boolean = true
    2. export function toggleObserving (value: boolean) {
    3. shouldObserve = value
    4. }
    它的作用就是修改当前模块的shouldObserve变量,用来控制在observe的过程中是否需要把当前值变成一个observer对象。 ```javascript

export function observe (value: any, asRootData: ?boolean): Observer | void { if (!isObject(value) || value instanceof VNode) { return } let ob: Observer | void if (hasOwn(value, ‘ob‘) && value.ob instanceof Observer) { ob = value.ob } else if ( shouldObserve && !isServerRendering() && (Array.isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue ) { ob = new Observer(value) } if (asRootData && ob) { ob.vmCount++ } return ob }

  1. 那么在处理props的过程中,什么时候toggleObserving(true),什么时候toggleObserving(false)以及为什么需要这样处理?
  2. ```javascript
  3. function initProps (vm: Component, propsOptions: Object) {
  4. if (!isRoot) {
  5. toggleObserving(false)
  6. }
  7. // 省略defineReactive的过程
  8. toggleObserving(true)
  9. }

props初始化的时候:
我们可以看到在最开始判断了当为非根实例(子组件)的时候,进行了toggleObserving(false)的操作,这样做的目的是因为:当非根实例的时候,组件的props来自于父组件。当props为对象或者数组时,根据响应式原理,我们会递归遍历子属性然后进行observe(val),而正是因为props来源于父组件,这个过程其实已经在父组件执行过了,如果不做任何限制,那么会在子组件中又重复一次这样的过程,因此这里需要toggleObserving(false),用来避免递归props子属性的情况,这属于响应式优化的一种手段。在代码最后,又调用了toggleObserving(true),把shouldObserve的值还原。
props校验的时候:
我们先来看props提供了default默认值,且默认值返回了对象或者数组。

  1. export default {
  2. props: {
  3. point: {
  4. type: Object,
  5. default () {
  6. return {
  7. x: 0,
  8. y: 0
  9. }
  10. }
  11. },
  12. list: {
  13. type: Array,
  14. default () {
  15. return []
  16. }
  17. }
  18. }
  19. }

对于以上point和list取默认值的情况,这个时候的props值与父组件没有关系,那么这个时候我们需要toggleObserving(true),在observe后再把shouldObserve变量设置为原来的值。

  1. export function validateProp () {
  2. // 省略代码
  3. if (value === undefined) {
  4. value = getPropDefaultValue(vm, prop, key)
  5. const prevShouldObserve = shouldObserve
  6. toggleObserving(true)
  7. observe(value)
  8. toggleObserving(prevShouldObserve)
  9. }
  10. }

在props更新的时候:
当父组件更新的时候,会调用updateChildComponent()方法,用来更新子组件的props值,这个时候其实和props初始化的逻辑一样,我们同样不需要对指向父组件的对象或数组props进行递归子属性observe的过程,因此这里需要执行toggleObserving(false)。

  1. export function updateChildComponent () {
  2. // update props
  3. if (propsData && vm.$options.props) {
  4. toggleObserving(false)
  5. const props = vm._props
  6. const propKeys = vm.$options._propKeys || []
  7. for (let i = 0; i < propKeys.length; i++) {
  8. const key = propKeys[i]
  9. const propOptions: any = vm.$options.props // wtf flow?
  10. props[key] = validateProp(key, propOptions, propsData, vm)
  11. }
  12. toggleObserving(true)
  13. vm.$options.propsData = propsData
  14. }
  15. }