Vue3 全局API 挂载

 1 import md5 from 'md5'
 2 
 3 // 创建 Vue 实例
 4 const app = createApp(App)
 5 
 6 // 把插件的 API 挂载全局变量到实例上
 7 app.config.globalProperties.$md5 = md5;
 8 
 9 // 你也可以自己写一些全局函数去挂载
10 app.config.globalProperties.$log = (text: string): void => {
11   console.log(text);
12 };
13 
14 app.mount('#app');

 

Vue3.x 中无法使用 this 来操作,所以要通过 getCurrentInstance 组件来进行处理

 1 // 导入 getCurrentInstance 组件
 2 import { defineComponent, getCurrentInstance } from 'vue'
 3 
 4 export default defineComponent({
 5   setup () {
 6     // 获取当前实例
 7     const app = getCurrentInstance();
 8 
 9     // 增加这层判断的原因见下方说明
10     if ( app ) {
11 
12       // 调用全局的 MD5 API 进行加密
13       const MD5_STR: string = app.appContext.config.globalProperties.$md5('Hello World!');
14       console.log(MD5_STR);
15 
16       // 调用刚刚挂载的打印函数
17       app.appContext.config.globalProperties.$log('Hello World!');
18 
19     }
20   }
21 })

 

来自于: https://vue3.chengpeiquan.com/plugin.html#使用全局-api-new

 
posted @ 2022-07-09 15:34  googlegis  阅读(557)  评论(0编辑  收藏  举报

坐标合肥,非典型GIS开发人员 GitHub