一、原型挂载
在vue3中没有 this 不再是实例化查出来的vue对象,那怎么往原型挂在公用的方法呢?
const app = createApp(App);
const test = () => {
console.log('我是测试函数触发的');
return '测试成功!';
};
app.config.globalProperties.$Test = test;
app.use(store).use(router).mount('#app')
二、使用方式
通过getCurrentInstance()获取当前组件实例,从而调用全局方法
import { getCurrentInstance } from 'vue';
setup(){
// getCurrentInstance() 获取当前组件实例
// 方式一,这种方式只能在开发环境下使用,生产环境下的ctx将访问不到
const { ctx } = getCurrentInstance();
// 方式二,此方法在开发环境以及生产环境下都能放到组件上下文对象(推荐)
const { proxy } = getCurrentInstance();
//调用方法;
proxy.$Test();
}