1、挂载和获取全局变量


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

首先在main.js中写入我们需要挂载的一个变量,比如一个地址吧
在这里插入图片描述

main.js

import { createApp } from 'vue'
import App from './App'
import store from '@store'
import router from '@router/index'


const app = createApp(App)
app.config.globalProperties.$httpUrl = 'https://www.baidu.com'
app.use(router)
    .use(store)
    .use(elementPlusUI)
    .mount('#app')

注意:千万不能这样子写:
第一种相当于我们直接调用了两次createApp(App),最后调的那次里面压根就没有我们需要配置的全局变量,会返回undefined


createApp(App).config.globalProperties.$httpUrl = 'https://www.baidu.com'
createApp(App).use(router)
    .use(store)
    .use(elementPlusUI)
    .mount('#app')

//或者是这样
const app = createApp(App)
createApp(App).config.globalProperties.$httpUrl = 'https://www.baidu.com'
app.use(router)
    .use(store)
    .use(elementPlusUI)
    .mount('#app')

在页面中获取也很简单,只需要从vue引入一个方法即可,不能在页面中使用this获取

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

这样就可以获取到挂载到全局中的变量了
在这里插入图片描述


2、优化


在项目中全局变量用的多了这样写就会很麻烦。每次都需要解构出来每次代码都是一样的,这时候我们可以把它封装成一个hooks

假设在main.js中有这4个全局变量

const app = createApp(App)
app.config.globalProperties.$a = 'a'
app.config.globalProperties.$b = 'b'
app.config.globalProperties.$c = 'c'
app.config.globalProperties.$d = 'd'

根目录下新建hooks/useGlobal.js

import {getCurrentInstance} from 'vue'

export default function useGetGlobalProperties() {
	const {emit, appContext: {app: {config: {globalProperties}}}} = getCurrentInstance()
	
	return {...globalProperties}
}

在某个文件中使用

<script setup>
import useGetGlobalProperties from '@/hooks/useGlobal'

const globalProperties = useGetGlobalProperties()
console.log('globalProperties-----', globalProperties)
</script>

在这里插入图片描述

利用这个hooks我们还能扩展一下,比如在里面加入一个vuex中的数据:获取当前系统主题色

import {computed, getCurrentInstance} from 'vue'
import {useStore} from 'vuex'

export default function useGetGlobalProperties() {
	const {emit, appContext: {app: {config: {globalProperties}}}} = getCurrentInstance()
	const store = useStore()
	
	const curThemeColor = computed(() => store.getters.themeColor)
	
	return {...globalProperties, curThemeColor}
}

在这里插入图片描述

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐