vue3的全局变量

500 阅读1分钟

vue2.x挂载全局是使用Vue.prototype.xxxx=xxx的形式来挂载,然后通过this.xxxx=xxx的形式来挂载,然后通过this.xxx来获取挂载到全局的变量或者方法 在vue3.x这种方法显然是不行了,vue3中在setup里面我们都获取不到this,官方提供了另一种方法来让我们使用, 上代码

首先在main.js中写入我们需要挂载的一个变量,比如一个地址吧

image.png

在组件里面使用

import { defineComponent, getCurrentInstance, onMounted } from "vue"
export default defineComponent({
	onMounted(() => {
      // console.log(this)
      const { appContext : { config: { globalProperties } } } = getCurrentInstance()
      console.log(globalProperties.$httpUrl)
    })
})

每一次都要导入,太麻烦了,直接封装一个hooks

// useGlobal.ts
import { getCurrentInstance } from 'vue'

export default function useGlobal() {
  const instance = getCurrentInstance();

  if (instance) {
    const { appContext: { app: { config: { globalProperties } } } } = instance;
    return { ...globalProperties };
  }

  return {};
}

使用

import useGlobal from '@/views/hooks/useGlobal';
const global = useGlobal();
//global.$echarts

使用echarts的彩蛋

vue2的写法
itemStyle: {
   shadowBlur: 10,
   shadowColor: 'rgba(120, 36, 50, 0.5)',
   shadowOffsetY: 5,
   //这里是全局导入的echarts
   color: new echarts.graphic.RadialGradient(0, 0, 0.1, [
   //global.$echarts.graphic.RadialGradient 这是vue3的按需导入写法
          {
            offset: 0,
            color: '#4DECA7'
          },
          {
            offset: 1,
            color: '#4DECA7'
           }
         ])
}