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>

打印结果:

 页面展示:

猜你喜欢

转载自blog.csdn.net/zhangdaiscott/article/details/131188718
今日推荐