zoukankan      html  css  js  c++  java
  • Vue3 getCurrentInstance与ts结合使用的问题

    关于Vue3里面的getCurrentInstance:可以获取挂载在全局的属性和获取上下文

    这里会碰到几个问题:

    一、不能使用getCurrentInstance的ctx

    我们在获取Vue3中全局挂载的方法时会这么写:

    这里的ctx不是setup提供的ctx

    const { ctx } = getCurrentInstance()

    这里ctx打包后在生产环境下是获取不到的,请各位没玩过生产的别不小心误导到别人啊哈,恰好在Vue3的issues中找到的。

    正确应该使用

    const { proxy } = getCurrentInstance()

    二、关于在ts中使用到类型定义错误问题

    报错:...类型“ComponentInternalInstance | null”

    就嗝屁了。。。

    1. 可以添加ts忽略去解决

      // @ts-ignore
      const { proxy } = getCurrentInstance();

    但是这个方法很无脑,也麻烦。。。

    2. 考虑到在获取上下文和全局挂载实例的时候会用到这个getCurrentInstance,那我们来新建 hooksuseCurrentInstance.ts

    import { ComponentInternalInstance, getCurrentInstance } from 'vue'
    export default function useCurrentInstance() {
        const { appContext } = getCurrentInstance() as ComponentInternalInstance
        const globalProperties = appContext.config.globalProperties
        return {
            globalProperties
        }
    }

    组件中使用

    // 先引入文件
    import useCurrentInstance from "@/hooks/useCurrentInstance";
    ...
    // 在setup 中使用处理
    const { globalProperties } = useCurrentInstance();

    注意的点:千万不要在getCurrentInstance() 中获取ctx来使用element等东西,这玩意在生成环境下结构就不一样了,会报undefined。可以使用proxy。(我第一次搞vue3就卡在这里2天)

  • 相关阅读:
    VS2015安装水晶报表
    C# 通过java生成的RSA公钥加密和解密
    T4代码生成器
    产品开发- DFX
    读《31天学会CRM项目开发》记录3
    读《31天学会CRM项目开发》记录2
    读《31天学会CRM项目开发》记录1
    产品开发
    产品开发
    机器视觉
  • 原文地址:https://www.cnblogs.com/mica/p/14756503.html
Copyright © 2011-2022 走看看