iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >使用vue3+ts+setup获取全局变量getCurrentInstance的方法实例
  • 448
分享到

使用vue3+ts+setup获取全局变量getCurrentInstance的方法实例

vue3获取全局变量vue3的setup函数vue3全局变量 2022-11-13 14:11:26 448人浏览 泡泡鱼
摘要

目录前言:vue3官方提供的方法1、引入方法2、定义变量,接到我们的方法3、main.js中定义我们的全局变量4、页面中使用我们的全局变量Vue3+ts 使用官方方法遇到的问题:最终

前言:

vue3的 setup中是获取不到this的,为此官方提供了特殊的方法,让我们可以使用this,达到我们获取全局变量的目的,但是在使用typescript的时候,就会有一些新的问题产生,这里来做一个整理。

vue3官方提供的方法

1、引入方法

import { getCurrentInstance } from 'vue'

2、定义变量,接到我们的方法

setup() {
    const { proxy } = getCurrentInstance()
}

3、main.js中定义我们的全局变量

app.config.globalProperties.$api = '111'

4、页面中使用我们的全局变量

setup() {
    const { proxy } = getCurrentInstance()
    console.log(proxy.$api)
}

vue3+ts 使用官方方法遇到的问题:

Property 'proxy' does not exist on type 'ComponentInternalInstance | null'

我在网上找的方法:网上资料入口

import { ComponentInternalInstance, getCurrentInstance } from 'vue';
// 添加断言
const { proxy } = getCurrentInstance() as ComponentInternalInstance

效果:不识别这种写法,不清楚是什么问题。多方尝试无果

最终我解决问题的方法:         

我把类型换成any,结果成功了,不知道原因,以后在查查资料

setup() {
   const { proxy } = getCurrentInstance() as any
}

补充:Vue3 getCurrentInstance与ts结合使用的问题

vue3项目中,如果不用ts这样使用是没问题的

const { proxy } = getCurrentInstance()

在ts中使用会报错:报错:...类型“ComponentInternalInstance | null”

我们在项目中一般会用到很多getCurrentInstance()方法,直接封装一下

创建useCurrentInstance.ts文件:

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

组件内使用:

<script lang="ts">
import { defineComponent } from "vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
export default defineComponent({
  setup() {
    const { proxy } = useCurrentInstance();
    console.log(proxy);
  },
});
</script>

总结

到此这篇关于使用vue3+ts+setup获取全局变量getCurrentInstance的文章就介绍到这了,更多相关vue3 ts setup获取全局变量内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: 使用vue3+ts+setup获取全局变量getCurrentInstance的方法实例

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

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

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

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

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

  • 微信公众号

  • 商务合作