# methods
function initMethods(vm: Component, methods: Object) {
const props = vm.$options.props;
for (const key in methods) {
if (process.env.NODE_ENV !== "production") {
if (typeof methods[key] !== "function") {
warn(
`Method "${key}" has type "${typeof methods[
key
]}" in the component definition. ` +
`Did you reference the function correctly?`,
vm
);
}
if (props && hasOwn(props, key)) {
warn(`Method "${key}" has already been defined as a prop.`, vm);
}
if (key in vm && isReserved(key)) {
warn(
`Method "${key}" conflicts with an existing Vue instance method. ` +
`Avoid defining component methods that start with _ or $.`
);
}
}
vm[key] =
typeof methods[key] !== "function" ? noop : bind(methods[key], vm);
}
}
- 判断传递的
methods是否是函数,如果不是,会报错误。 - 判断传递的
key是否在props中,如果不是,会报错误。 - 最后判断传入的
key是以_和$开头并且属于vm,也会报错。 - 如果不是函数,直接返回空函数,否则就
bind传递对应的vm。