您好,欢迎来到意榕旅游网。
搜索
您的当前位置:首页详解Vue内部怎样处理props选项的多种写法

详解Vue内部怎样处理props选项的多种写法

来源:意榕旅游网
详解Vue内部怎样处理props选项的多种写法

开发过程中,props 的使⽤有两种写法:

// 字符串数组写法

const subComponent = { props: ['name']}

// 对象写法

const subComponent = { props: { name: {

type: String,

default: 'Kobe Bryant' } }}

Vue在内部会对 props 选项进⾏处理,⽆论开发时使⽤了哪种语法,Vue都会将其规范化为对象的形式。具体规范⽅式见src/core/util/options.js ⽂件中的 normalizeProps 函数:

/**

* Ensure all props option syntax are normalized into the

* Object-based format.(确保将所有props选项语法规范为基于对象的格式) */

// 参数的写法为 flow(https://flow.org/) 语法

function normalizeProps (options: Object, vm: ?Component) { const props = options.props

// 如果选项中没有props,那么直接return if (!props) return

// 如果有,开始对其规范化

// 声明res,⽤于保存规范化后的结果 const res = {} let i, val, name

if (Array.isArray(props)) { // 使⽤字符串数组的情况 i = props.length

// 使⽤while循环遍历该字符串数组 while (i--) { val = props[i]

if (typeof val === 'string') {

// props数组中的元素为字符串的情况

// camelize⽅法位于 src/shared/util.js ⽂件中,⽤于将中横线转为驼峰 name = camelize(val) res[name] = { type: null }

} else if (process.env.NODE_ENV !== 'production') {

// props数组中的元素不为字符串的情况,在⾮⽣产环境下给予警告 // warn⽅法位于 src/core/util/debug.js ⽂件中

warn('props must be strings when using array syntax.') } }

} else if (isPlainObject(props)) { // 使⽤对象的情况(注)

// isPlainObject⽅法位于 src/shared/util.js ⽂件中,⽤于判断是否为普通对象 for (const key in props) { val = props[key]

name = camelize(key)

// 使⽤for in循环对props每⼀个键的值进⾏判断,如果是普通对象就直接使⽤,否则将其作为type的值 res[name] = isPlainObject(val) val

: { type: val } }

} else if (process.env.NODE_ENV !== 'production') {

// 使⽤了props选项,但它的值既不是字符串数组,⼜不是对象的情况

// toRawType⽅法位于 src/shared/util.js ⽂件中,⽤于判断真实的数据类型 warn(

`Invalid value for option \"props\": expected an Array or an Object, ` + `but got ${toRawType(props)}.`, vm ) }

options.props = res}

如此⼀来,假如我的 props 是⼀个字符串数组:

props: [\"team\"]

经过这个函数之后,props 将被规范为:

props: { team:{ type: null }}

假如我的 props 是⼀个对象:

props: {

name: String, height: {

type: Number, default: 198 }}

经过这个函数之后,将被规范化为:

props: { name: {

type: String },

height: {

type: Number, default: 198 }}

注:对象的写法也分为以下两种,故仍需进⾏规范化

props: {

// 第⼀种写法,直接写类型 name: String,

// 第⼆种写法,写对象 name: {

type: String,

default: 'Kobe Bryant' }}

最终会被规范为第⼆种写法。

以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- yrrf.cn 版权所有 赣ICP备2024042794号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务