当前位置:首页 > 开发教程 > js/jQuery教程 >

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

时间:2022-05-24 15:32 来源:未知 作者:天大地 收藏

这篇文章主要介绍了vue3?解决getCurrentInstance?打包后线上环境报错问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

getCurrentInstance

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

WARNING

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

import { getCurrentInstance } from 'vue'
const MyComponent = {
  setup() {
    const internalInstance = getCurrentInstance()
 
    internalInstance.appContext.config.globalProperties // 访问 globalProperties
  }
}

打印信息:

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

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>

查看打印:

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

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

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

方法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;
            }
          });
        }
}

打印:

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

到此这篇关于vue3 解决getCurrentInstance 打包后线上环境报错问题的文章就介绍到这了,更多相关vue3 getCurrentInstance 打包报错内容请搜索源码搜藏网以前的文章或继续浏览下面的相关文章希望大家以后多多支持源码搜藏网!


js/jQuery教程阅读排行

最新文章