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

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐