1. 定义全局变量的方式
main.ts 中,获取到 app 实例后
const app = createApp(App),借助其身上的一些属性来挂载全局变量和函数
挂载 ↓
app.config.globalProperties.name = value
其中 name 就是名称,value 可以是属性、函数、对象等,和普通的定义一样
2. 声明代码
由于 vue 中本身并没有我们自定义并挂载到其身上的全局变量,所有需要为这些全局变量声明一下,不然使用的时候会报错,但还是可以用
const app = createApp(App)
// 挂载属性
app.config.globalProperties.$env = 'dev'
// 挂载函数
app.config.globalProperties.$filter = <T>(str: T) => {
return 'lzy-' + str
}
// 挂载对象
app.config.globalProperties.$filters = {
format<T> (str: T){
return 'lzy-' + str
}
}
type Filter = {
format<T> (str: T):string
}
// 为这些自定义的全局变量作声明
declare module 'vue' {
export interface ComponentCustomProperties {
$filters: Filter,
$filter: Function,
$env: string
}
}
3. 使用
在模板中使用:直接用定义的变量名即可
<template>
<div>{{ $env }}</div>
<div>{{ $filters.format('过滤器') }}</div>
<div>{{ $filter('过滤器') }}</div>
</template>
在 js 中使用:需要借助 `getCurrentInstance()` 先获取 app 实例,然后以 `app?.proxy?.` 的方式获取变量
<script setup lang="ts">
import { getCurrentInstance } from 'vue';
const app = getCurrentInstance()
console.log(app?.proxy?.$env)
console.log(app?.proxy?.$filter('ts1'))
console.log(app?.proxy?.$filters.format('ts2'))
</script>