Vue3_29(定义全局函数和变量)

2023-01-07  本文已影响0人  BingJS

globalProperties

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

Vue.prototype.$http = () => {}

Vue3:

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);
上一篇下一篇

猜你喜欢

热点阅读