vue3 - 21.定义全局函数&变量

globalProperties

定义全局函数和变量:vue2 的写法:

vue.prototype.$varName = () => {}

定义全局函数和变量:vue3 的写法:

const app = createApp(App)
app.config.globalProperties.$varName = () => {}

案例1:

main.ts

import { createApp} from 'vue'
const app = createApp(App)

type SAY = {
    format: (str: T) => string
}
declare module '@vue/runtime-core' {
    export interface ComponentCustomProperties {
        $varName: SAY,
        $env: string
    }
}
app.config.globalProperties.$varName = {
    format(str: T): string {
        return 'say' + `${str}`
    }
}
app.config.globalProperties.$env = 'dev'

index.vue