关于vue3:vue3全局变量的使用

一、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>

打印后果:

页面展现:

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理