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

1次阅读

共计 618 个字符,预计需要花费 2 分钟才能阅读完成。

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

打印后果:

页面展现:

正文完
 0