在vue3中如何定义全局变量和方法

  • Post author:
  • Post category:vue



Vue2中:

// 之前 (Vue 2.x)
Vue.prototype.$http = () => {}


Vue3:

// 之后 (Vue 3.x)
const app = createApp({})
app.config.globalProperties.$http = () => {}


过滤器

已被移除,我们刚好可以用全局方法:

app.config.globalProperties.

KaTeX parse error: Expected ‘}’, got ‘EOF’ at end of input: … { return `

${str}`

}

}

声明文件 不然TS无法正确类型 推导

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

setup读取值

import { getCurrentInstance, ComponentInternalInstance } from 'vue';
 
const { appContext } = <ComponentInternalInstance>getCurrentInstance()
 
console.log(appContext.config.globalProperties.$env);
 
推荐第二种方式
 
import {ref,reactive,getCurrentInstance} from 'vue'
const app = getCurrentInstance()
console.log(app?.proxy?.$filters.format('js'))

我们还可以用全局注入的方式:

先定义一个文件api.js

import http from "./http";

export const api = {
    async getUserInfo(){
        return await http.get('/userInfo')
    }
}

main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import { api } from "@/api/index";
onst app = createApp(App)
app.use(store).use(router).mount('#app')
app.provide('api', api);//全局发送api

任何一个子组件child.js

<script>
import { useStore } from "vuex";
import { inject, onBeforeMount, ref } from "vue";
export default {
    name: 'Child',
    setup(props) {
        const $http = inject('api')
        onBeforeMount(async() => {
            const res = await $http.getUserInfo()
            console.log(res);
            //...其余操作
        })
    },
}
</script>



版权声明:本文为qq_42931285原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。