美文网首页
Vue3_29(定义全局函数和变量)

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

作者: BingJS | 来源:发表于2023-01-07 13:54 被阅读0次

    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);
    

    相关文章

      网友评论

          本文标题:Vue3_29(定义全局函数和变量)

          本文链接:https://www.haomeiwen.com/subject/sheyjrtx.html