一、main.ts中定义

image

二、在页面中使用

<template>
  <div>
    全局变量
    <div>方法1(使用 getCurrentInstance 的 appContext):{{way1}}</div>
    <div>方法2(从 getCurrentInstance 结构出 proxy):{{way2}}</div>
  </div>
</template>

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

export default defineComponent({
  name:'board',
  setup() {
    const { proxy } = getCurrentInstance() as any;
    const data = reactive({
      way1:  getCurrentInstance()?.appContext.config.globalProperties.$message,
      way2: proxy.$message,
    })
    
    onMounted(()=>{
      // 打印
      console.log(data.way1,'方法1')
      console.log(data.way2,'方法2')
    })
    
    return {
      ...toRefs(data),
    }
  },
})
</script>

<style scoped lang="less">

</style>

打印结果:
image
页面展示:
image

posted on 2023-06-13 15:29  zhangdaiscott  阅读(695)  评论(0)    收藏  举报