一、main.ts中定义
二、在页面中应用
<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>
打印后果:
页面展现: