20.Vue3全局变量和函数

749 阅读1分钟

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

Vue2.x
// 这样就在全局添加了一个$http方法
Vue.prototype.$http = () => {}
Vue3.x
// 这样就在实例对象上添加了一个$http方法
const app = createApp({})
app.config.globalProperties.$http = () => {}

案例

// App.vue
import {createApp} from 'vue'
import App from './App.vue'

const app = createApp(App)

// 声明类型
interface Filter {
    format: <T extends any>(str: T) => T
}

// 声明要扩充@vue/runtime-core包的声明,不然模版中无法正确提示。
// 这里扩充"ComponentCustomProperties"接口,因为他是vue3中实例的属性的类型。
// 注:相同名字的interface会进行合并操作。
declare module '@vue/runtime-core' {
    export interface ComponentCustomProperties {
        $filters: Filter
    }
}
// 全局注册方法
app.config.globalProperties.$filters = {
    format<T>(str: T): string {
        return `2022-${str}`
    }
}
app.mount('#app')

在setup中读取值

<template>
  <!--直接使用-->
  {{ $filters.format('08-02') }}
</template>
<script setup lang="ts">
// 在setup中想拿到全局的方法或者属性
import {ComponentInternalInstance, getCurrentInstance} from 'vue'
// getCurrentInstance方法可以获取当前的Vue实例
const {appContext} = <ComponentInternalInstance>getCurrentInstance()
// 这样就可以拿到这个方法
console.log(appContext.config.globalProperties.$filters.format)
</script>
<style lang="scss"></style>