vue3 解决getCurrentInstance 打包后线上环境报错问题

138 篇文章 7 订阅
64 篇文章 4 订阅

getCurrentInstance

getCurrentInstance 支持访问内部组件实例。

WARNING

getCurrentInstance 只暴露给高阶使用场景,典型的比如在库中。强烈反对在应用的代码中使用 getCurrentInstance。请不要把它当作在组合式 API 中获取 this 的替代方案来使用。

import { getCurrentInstance } from 'vue'

const MyComponent = {
  setup() {
    const internalInstance = getCurrentInstance()

    internalInstance.appContext.config.globalProperties // 访问 globalProperties
  }
}

打印信息: 

6d4729c87a6647328aa7e6b8df555062.png

getCurrentInstance 只能在setup或生命周期钩子中调用。 

如需在 setup或生命周期钩子外使用,请先在 setup 中调用 getCurrentInstance() 获取该实例然后再使用。

setup() {
    const internalInstance = getCurrentInstance() // 有效

    const id = useComponentId() // 有效

    const handleClick = () => {
      getCurrentInstance() // 无效
      useComponentId() // 无效

      internalInstance // 有效
    }
}

本地使用示例:

当前在本地使用没有问题,线上环境会报错,不建议使用

<script>
    import {getCurrentInstance} from "vue";
    export default {
      components: {
        
      },
      setup() {
         const {ctx} = getCurrentInstance();
         console.log(ctx,"属性1")
         
  
      }
    
</script>

查看打印:

5ce3ff9008324d0d9ce97ad675b1b14a.png

项目中使用:表单table列表查询

ee8390d8ed874861bc24948e1adeb8d5.png

方法1: 不推荐

setup() {
         const {ctx} = getCurrentInstance();
         console.log(ctx,"属性1")
         
        //表单查询方法
        const submitForm = (formName) =>{
          ctx.$refs[formName].validate(valid => {
            if (valid) {
              ruleForm.pageNum = 1;
              getTableData();
            } else {
              console.log("error submit!!");
              return false;
            }
          });
        }
}

 方法2:推荐此用法,才能在你项目正式上线版本正常运行,避免线上报错问题

解决:用proxy代替ctx。在结构的时候直接将proxy解构出来

setup() {
         let {proxy} = getCurrentInstance();
        console.log(proxy,"属性2");
         
        //表单查询方法
        const submitForm = (formName) =>{
          proxy.$refs[formName].validate(valid => {
            if (valid) {
              ruleForm.pageNum = 1;
              getTableData();
            } else {
              console.log("error submit!!");
              return false;
            }
          });
        }
}

打印:

45add841760b4667be12dbec82b8f312.png

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

船长在船上

您的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值