A deep dive in the Vue.js source code (#10): the normalizeProps function (continued)

This is the tenth post in a series examining the Vue.js source code line-by-line. In the last post, we examined the camelize function in order to better understand what is happening in the normalizeProps function. In this post, we turn back to the code of the normalizeProps function.

normalizeProps ensures “all props option syntax are normalized into the Object-based format”

When we last left off, we were here:

function normalizeProps (options, vm) {
var props = options.props;
if (!props) { return }
var res = {};
var i, val, name;
if (Array.isArray(props)) {
i = props.length;
while (i--) {
val = props[i];
if (typeof val === 'string') {
name = camelize(val);
res[name] = { type: null };
} else if (process.env.NODE_ENV !== 'production') {
warn('props must be strings when using array syntax.');
}
}
} else if (isPlainObject(props)) {
for (var key in props) {
val = props[key];
name = camelize(key);
res[name] = isPlainObject(val)
? val
: { type: val };
}
} else if (process.env.NODE_ENV !== 'production') {
warn(
"Invalid value for option \"props\": expected an Array or an Object, " +
"but got " + (toRawType(props)) + ".",
vm
);
}
options.props = res;
}

Now that we have reviewed the camelize function, we understand thatcamelize first checks the cache object (wrapped in a closure) to determine whether the passed value (here, val) matches a property/key on the cache object. If val has already been cached, the camelize function returns the previously cached result. If val has not been cached, the camelize function calls the String replace() method to replace the hyphen and the first letter after the hyphen in a word. camelize replaces hyphen delimited words by removing the hyphen and uppercasing the first letter after the hyphen.

Next, the normalizeProps function: (1) sets a property on the res object with the newly camelized value (i.e., name) as the property name, (2) initializes it as an object, and (3) sets a property on the object named type to null.

res[name] = { type: null };

If the type of val is not a string and if you are in a development environment, the normalizeProps function calls the warn function and passes a string as a parameter stating, “props must be strings when using array syntax.”

     if (typeof val === 'string') {
name = camelize(val);
res[name] = { type: null };
} else if (process.env.NODE_ENV !== 'production') {
warn('props must be strings when using array syntax.');
}

If you like the series and want to motivate me to keep working through it, please feel free to clap, follow, respond, or share to your heart’s content.

As promised in a previous post, we will take a look at the warn function in the next post.