vue3获取当前组件实例的方法getCurrentInstance

在vue3中,setup 是围绕 beforeCreate 和 created 生命周期钩子运行的,setup的执行时组件对象还没有创建,此时不能使用this来访问data/computed/methods/props,我们可以通过 getCurrentInstance这个函数来返回当前组件的实例对象,也就是当前vue这个实例对象
开发模式:

import { getCurrentInstance, onMounted, ref } from 'vue'
export default ({
    components:{
        Header
    },
    setup(props, context) {
        const { ctx } = getCurrentInstance()
        onMounted(()=>{
           ctx.$http.get('/user')
        })
        return {
        }
    }

在生产环境,无法获取全局上挂载的方法。不要依赖 ctx 方法去获取组件实例来完成一些主要功能,否则在项目打包后会报错。
解决办法是用proxy代替ctx.

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐