globalProperties

由于Vue3 没有Prototype 属性 使用 app.config.globalProperties 代替 然后去定义变量和函数
Vue2

  1. // 之前 (Vue 2.x)
  2. Vue.prototype.$http = () => {}

Vue3

  1. // 之后 (Vue 3.x)
  2. const app = createApp({})
  3. app.config.globalProperties.$http = () => {}

过滤器

在Vue3 移除了
我们正好可以使用全局函数代替Filters
案例

  1. app.config.globalProperties.$filters = {
  2. format<T extends any>(str: T): string {
  3. return `$${str}`
  4. }
  5. }

声明文件 不然TS无法正确类型 推导

  1. type Filter = {
  2. format: <T extends any>(str: T) => T
  3. }
  4. // 声明要扩充@vue/runtime-core包的声明.
  5. // 这里扩充"ComponentCustomProperties"接口, 因为他是vue3中实例的属性的类型.
  6. declare module '@vue/runtime-core' {
  7. export interface ComponentCustomProperties {
  8. $filters: Filter
  9. }
  10. }

setup 读取值

  1. import { getCurrentInstance, ComponentInternalInstance } from 'vue';
  2. const { appContext } = <ComponentInternalInstance>getCurrentInstance()
  3. console.log(appContext.config.globalProperties.$env);