vue3的全局变量以及解决报错

741 阅读1分钟

vue2的过滤器已经舍弃了,之前的全局变量是 Vue.prototype.$http = () => {}去定义

vue3在main.ts里面定义全局变量和函数,

//变量
app.config.globalProperties.$Dev = 'dev'
//函数
app.config.globalProperties.$filters = {
    format<T>(str:T){
        return `lihk + ${str}`
    }
}

image.png

使用是会报错,需要声明变量的类型

type Filter = {
    format<T>(str: T): string
}
 
// 声明要扩充@vue/runtime-core包的声明.
// 这里扩充"ComponentCustomProperties"接口, 因为他是vue3中实例的属性的类型.
declare module 'vue' {
    export interface ComponentCustomProperties {
        $filters: Filter,
        $Dev:string
    }
}