前言
众所周知,我们在某些项目开发场景下有时候需要通过安装全局可用的属性来解决一些共性问题。举例来说,我们可能为了统一请求方式而需要自定义安装$http这样一个全局属性。
在Vue2中,我们经常使用 Vue.prototype 这一方式进行实现。但是,此写法在 Vue 3 已经不存在了。因为,作者认为与任何全局的东西一样,应该谨慎使用。
那我们应该如何使用呢,在Vue3中,需要使用app.config.globalProperties这一对象进行注入。我们通过$http这个案例,从挂载和声明两个方面展开说下
一、挂载全局属性
1.注册
新建globalProperties.ts进行存储我们需要注册的所有全局对象
export const globalProperties = {
install(app: App){
// 定义全局$https
app.config.globalProperties.$http= {
get: function(url: string, data: any){
// 请求逻辑
}
}
}
}
2.挂载注册
在main.ts文件中,我们使用app.use注册该文件
import { globalProperties } from './globalProperties'
...
...
const app = createApp(App)
// 注册全局变量
app.use(globalProperties);
app.mount('#app')
3.使用
在组件中,我们通过getCurrentInstance这个api进行获取及调用(虽然官方不太推荐这个方法,但是好像没有更加灵活的方式了)
<script setup lang="ts">
import { getCurrentInstance, onBeforeMount, type ComponentInternalInstance } from 'vue';
const currentInstance= getCurrentInstance() as ComponentInternalInstance;
const globalProperties = currentInstance?.appContext.config.globalProperties
onBeforeMount(() => {
// 通过globalProperties对象获取我们注册的全局对象
globalProperties.$https.get('请求地址',{})
})
</script>
二、声明全局属性
在vue3+typeScript下,如果没有类型标注的话,我们在使用的过程中经常会出现标红或者报错,影响我们的开发体验,所以我们需要进行声明这些全局属性
官方文档中关于标注的使用有说明 扩展全局属性
1.类型约定
新增types.ts文件,用于类型约定
export interface HttpType{
get:(url: string, params: any)=> Promise<any>;
}
2.类型注册
新建global-properties.d.ts文件,用于类型注册
import type { HttpType} from "./types"
declare module 'vue' {
interface ComponentCustomProperties {
$http: HttpType
}
}
export {}
注意,在global-properties.d.ts文件中,我们也需要将global-properties.d.ts文件包含进行,这样子项目运行的时候,才能自动解析进去
"include": ["global-properties.ts",...]
总结
这样子我们就可以在开发过程中自由使用全局属性了