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

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.

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值