feat(runtime-core): warn against user properties with reserved prefixes

This commit is contained in:
Evan You 2020-05-01 11:23:01 -04:00
parent 20bc7ba1c5
commit 1bddeea247
2 changed files with 30 additions and 11 deletions

View File

@ -417,12 +417,14 @@ export function applyOptions(
for (const key in rawData) { for (const key in rawData) {
checkDuplicateProperties!(OptionTypes.DATA, key) checkDuplicateProperties!(OptionTypes.DATA, key)
// expose data on ctx during dev // expose data on ctx during dev
Object.defineProperty(ctx, key, { if (key[0] !== '$' && key[0] !== '_') {
configurable: true, Object.defineProperty(ctx, key, {
enumerable: true, configurable: true,
get: () => rawData[key], enumerable: true,
set: NOOP get: () => rawData[key],
}) set: NOOP
})
}
} }
} }
} }

View File

@ -195,10 +195,19 @@ export const PublicInstanceProxyHandlers: ProxyHandler<any> = {
) { ) {
return globalProperties[key] return globalProperties[key]
} else if (__DEV__ && currentRenderingInstance) { } else if (__DEV__ && currentRenderingInstance) {
warn( if (data !== EMPTY_OBJ && key[0] === '$' && hasOwn(data, key)) {
`Property ${JSON.stringify(key)} was accessed during render ` + warn(
`but is not defined on instance.` `Property ${JSON.stringify(
) key
)} must be accessed via $data because it starts with a reserved ` +
`character and is not proxied on the render context.`
)
} else {
warn(
`Property ${JSON.stringify(key)} was accessed during render ` +
`but is not defined on instance.`
)
}
} }
}, },
@ -280,7 +289,15 @@ export const RuntimeCompiledPublicInstanceProxyHandlers = {
return PublicInstanceProxyHandlers.get!(target, key, target) return PublicInstanceProxyHandlers.get!(target, key, target)
}, },
has(_: ComponentRenderContext, key: string) { has(_: ComponentRenderContext, key: string) {
return key[0] !== '_' && !isGloballyWhitelisted(key) const has = key[0] !== '_' && !isGloballyWhitelisted(key)
if (__DEV__ && !has && PublicInstanceProxyHandlers.has!(_, key)) {
warn(
`Property ${JSON.stringify(
key
)} should not start with _ which is a reserved prefix for Vue internals.`
)
}
return has
} }
} }