globalProperties
由于Vue3 没有Prototype 属性 使用 app.config.globalProperties 代替 然后去定义变量和函数
Vue2
// 之前 (Vue 2.x)Vue.prototype.$http = () => {}
Vue3
// 之后 (Vue 3.x)const app = createApp({})app.config.globalProperties.$http = () => {}
过滤器
在Vue3 移除了
我们正好可以使用全局函数代替Filters
案例
app.config.globalProperties.$filters = {format<T extends any>(str: T): string {return `$${str}`}}
声明文件 不然TS无法正确类型 推导
type Filter = {format: <T extends any>(str: T) => T}// 声明要扩充@vue/runtime-core包的声明.// 这里扩充"ComponentCustomProperties"接口, 因为他是vue3中实例的属性的类型.declare module '@vue/runtime-core' {export interface ComponentCustomProperties {$filters: Filter}}
setup 读取值
import { getCurrentInstance, ComponentInternalInstance } from 'vue';const { appContext } = <ComponentInternalInstance>getCurrentInstance()console.log(appContext.config.globalProperties.$env);
