Vue3 总结梳理

持续更新中 …

vue3.x 如何注册全局组件/方法(替代vue2.x的Vue.prototype)

比如将 axios 等第三方组件, 进行全局注册,方便全局中使用。

Vue 2 中,一般可以定义在 Vue 原型上

// main.js
import Vue from 'vue';
import App from './App';
import axios from 'axios';

Vue.prototype.$axios = axios
//...

然后就可以在任何 Vue 实例中使用类似 this.$axios.get 的方法。

Vue3 中

(一)利用 config.globalProperties(不推荐):

// main.js
const app = createApp({})
app.config.globalProperties.$axios = axios

Vue3 中没有 this ,getCurrentInstance 支持访问内部组件实例。在组件中,通过getCurrentInstance().appContext.config.xxx 获取并调用:

import { onMounted, getCurrentInstance } from 'vue';

onMounted(() => {
     getCurrentInstance().appContext.config.$axios
});

getCurrentInstance 只暴露给高阶使用场景,典型的比如在库中。强烈反对在应用的代码中使用 getCurrentInstance。请不要把它当作在组合式 API 中获取 this 的替代方案来使用。

可见:官方反对我们这样使用 getCurrentInstance,可以采取以下方式:

(二)利用 provide / inject (✨推荐):

// main.js
import { createApp } from 'vue';
import App from './App.vue';
import axios from 'axios';

const app = createApp(App);
app.provide('$axios', axios)

app.mount('#app');

组件中,通过 inject 获取并调用:

import { onMounted, inject } from 'vue';

onMounted(() => {
     const http = inject('$axios')
     http.get()
     // ...
});

vue3.x 如何按需引入三方组件库,如 vant

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值