iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >关于vue3 解决getCurrentInstance 打包后线上环境报错问题
  • 820
分享到

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

2024-04-02 19:04:59 820人浏览 泡泡鱼
摘要

getCurrentInstance getCurrentInstance 支持访问内部组件实例。 WARNING getCurrentInstance 只暴露给

getCurrentInstance

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

WARNING

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

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

打印信息: 

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>

查看打印:

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

方法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 打包报错内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: 关于vue3 解决getCurrentInstance 打包后线上环境报错问题

本文链接: https://www.lsjlt.com/news/149608.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作