feat(runtime-vapor): add globalProperties

This commit is contained in:
三咲智子 Kevin Deng 2024-05-17 20:38:57 +08:00
parent 1b2cb722fe
commit f5f1150d8a
No known key found for this signature in database
1 changed files with 29 additions and 0 deletions

View File

@ -100,6 +100,7 @@ export function createAppContext(): AppContext {
config: { config: {
errorHandler: undefined, errorHandler: undefined,
warnHandler: undefined, warnHandler: undefined,
globalProperties: {},
}, },
provides: Object.create(null), provides: Object.create(null),
} }
@ -131,6 +132,7 @@ export interface AppConfig {
instance: ComponentInternalInstance | null, instance: ComponentInternalInstance | null,
trace: string, trace: string,
) => void ) => void
globalProperties: ComponentCustomProperties & Record<string, any>
} }
export interface AppContext { export interface AppContext {
@ -144,3 +146,30 @@ export interface AppContext {
* `app.runWithContext()`. * `app.runWithContext()`.
*/ */
export let currentApp: App | null = null export let currentApp: App | null = null
/**
* Custom properties added to component instances in any way and can be accessed through `this`
*
* @example
* Here is an example of adding a property `$router` to every component instance:
* ```ts
* import { createApp } from 'vue'
* import { Router, createRouter } from 'vue-router'
*
* declare module '@vue/runtime-core' {
* interface ComponentCustomProperties {
* $router: Router
* }
* }
*
* // effectively adding the router to every component instance
* const app = createApp({})
* const router = createRouter()
* app.config.globalProperties.$router = router
*
* const vm = app.mount('#app')
* // we can access the router from the instance
* vm.$router.push('/')
* ```
*/
export interface ComponentCustomProperties {}