您现在的位置是:网站首页> 编程资料编程资料
使用vue3+ts+setup获取全局变量getCurrentInstance的方法实例_vue.js_
2023-05-24
377人已围观
简介 使用vue3+ts+setup获取全局变量getCurrentInstance的方法实例_vue.js_
前言:
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 } }组件内使用:
总结
到此这篇关于使用vue3+ts+setup获取全局变量getCurrentInstance的文章就介绍到这了,更多相关vue3 ts setup获取全局变量内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
您可能感兴趣的文章:
相关内容
- vuex 设计思路和实现方式_vue.js_
- vue3+ts如何通过lodash实现防抖节流详解_vue.js_
- vue项目中更改名字和图标的简单实现步骤_vue.js_
- vue获取input值的三种常用写法_vue.js_
- Vue中的table表单切换实现效果_vue.js_
- Typescript中extends关键字的基本使用_javascript技巧_
- vue获取el-form的整体验证状态_vue.js_
- vue中使用@blur获取input val值_vue.js_
- jQuery编程动画的基本方法示例详解_jquery_
- uniapp下单选框的实现方法详解_javascript技巧_
