vue3+ts使用app.config.globalProperties全局挂载实例

1,835 阅读1分钟

main.ts

import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)

// 全局的属性
app.config.globalProperties.$hello = 'hello world'
app.config.globalProperties.$sayHello = () => console.log('你好呀')

app.mount('#app')

Demo.vue

<script lang="ts">
import { defineComponent, getCurrentInstance } from 'vue'

// 为了告诉 TypeScript 这些新 property,我们需要使用[模块扩充]
declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $hello: string
    $sayHello: () => void
  }
}

export default defineComponent({
  name: 'Demo-Component',
  setup() {
    const currentInstance = getCurrentInstance()
    console.log(currentInstance?.proxy?.$hello)
    currentInstance?.proxy?.$sayHello()
    // 或者
    // console.log(currentInstance?.appContext.config.globalProperties.$hello)
    // currentInstance?.appContext.config.globalProperties.$sayHello()
  },
})
</script>