v3项目实战-2

43 阅读1分钟

24.全局变量/函数

// main.ts中声明一个变量$env/$filter
main.ts中:
type Filter = {
    format<T>(str: T): string
}
app.config.globalProperties.$env = 'dev'
app.config.globalProperties.$filters = {
    format<T>(str: T) {
        return `123-${str}`
    }
}



// app中使用
// template/js中使用
app中:
<div>{{ $env }}</div>
<div>{{ $filters.format("wodewode") }}</div>


<script setup lang="ts">
    import { getCurrentInstance } from "vue"
    const app = getCurrentInstance()
    console.log(app?.proxy?.$env)
</script>


// app中$env/$filters报错,∵TS类型判断失败,在main.ts中加入ts注册
// 这个无效
declare module 'vue' {
    export interface ComponentCustomProperties {
        $env: string,
        $filters: Filter,
        $Bus: typeof Mit,
    }
}
// 这个可以
declare module '@vue/runtime-core' {
    export interface ComponentCustomProperties {
        $env: string,
        $filters: Filter,
        $Bus: typeof Mit,
    }
}

25.vue插件编写