vue3.x是无法通过Vue.prototype来注册全局组件/方法的,因此需要另辟蹊径。
vue3.x注册全局组件/方法主要有以下两个方式:
provide / inject (推荐)
main.js中:通过provide将组件或者方法、变量挂载在全局
import { createApp } from'vue'; importAppfrom'./App.vue'; importrouterfrom'./router'; importstorefrom'./store'; constapp=createApp(App); app.use(store); app.use(router); // 挂载全局方法constglobalFunc= () => { console.log('要挂载在全局的方法'); } // 将globalFunc方法挂载在全局app.provide('globalFunc', globalFunc); app.mount('#app'); // 把vue实例挂载在window.vm,方便使用vue的实例window.vm=app;
组件中:通过inject获取全局方法并调用
<template><div>组件中通过inject获取全局方法并调用</div></template><scriptlang="ts">import { defineComponent, onMounted, inject } from'vue'; exportdefaultdefineComponent({ name: 'JobDetail', // 注册组件components: { Header, }, setup() { onMounted(() => { testFunc(); }); consttestFunc= (): void=> { constglobalFunc: any=inject('globalFunc'); // 通过inject获取挂载在全局的globalFunc方法globalFunc(); }; return { testFunc, }; }, }); </script>
app.config.globalProperties(不推荐)
main.js中:通过app.config.globalProperties将组件或者方法、变量挂载在全局
import { createApp } from'vue'; importAppfrom'./App.vue'; importrouterfrom'./router'; importstorefrom'./store'; constapp=createApp(App); app.use(store); app.use(router); // 挂载全局方法constglobalFunc= () => { console.log('要挂载在全局的方法'); } // 将globalFunc方法挂载在全局app.config.globalProperties.globalFunc=globalFunc; app.mount('#app'); // 把vue实例挂载在window.vm,方便使用vue的实例window.vm=app;
组件中:通过getCurrentInstance().appContext.config.globalProperties获取全局方法并调用
<template><div>组件中通过inject获取全局方法并调用</div></template><scriptlang="ts">import { defineComponent, onMounted, getCurrentInstance } from'vue'; exportdefaultdefineComponent({ name: 'JobDetail', // 注册组件components: { Header, }, setup() { onMounted(() => { testFunc(); }); consttestFunc= (): void=> { constinternalInstance: any=getCurrentInstance(); console.log(internalInstance.appContext.config.globalProperties); // 通过getCurrentInstance().appContext.config.globalProperties获取全局方法并调用internalInstance.appContext.config.globalProperties.globalFunc(); }; return { testFunc, }; }, }); </script>
需要注意的是:
vue3官网提示
getCurrentInstance only works during setup or Lifecycle Hooks
When using outside of setup or Lifecycle Hooks, please call getCurrentInstance() on setup and use the instance instead.
文章参考:
https://www.5axxw.com/questions/content/nsd3mq
https://www.cnblogs.com/xiaoyan2017/p/14221729.html
https://www.freesion.com/article/40251353944/
https://blog.csdn.net/weixin_43273755/article/details/115311398
————————————————
版权声明:本文为CSDN博主「Boale_H」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Boale_H/article/details/118857338