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

225 篇文章 1 订阅
199 篇文章 4 订阅

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>
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值