vue3导入全局变量时,可以运行但是会一直显示报错如图

 解决方法如下

在 Vue.js 3 中,”@vue/runtimecore” 是一个包含 Vue.js 运行核心模块这个模块提供了一些关键的 Vue.js 核心类型方法例如创建 Vue 实例虚拟 DOM 渲染组件渲染等等。当我们在 Vue.js 3 的项目使用 TypeScript 进行编程时,我们需要使用“@vue/runtimecore模块引入这些类型方法

使用 TypeScript 编写 Vue.js 3 项目时,我们通常会使用 “.d.ts文件描述 Vue.js 相关类型信息。在这些文件中,我们需要声明”@vue/runtimecore模块类型信息以便在我们的项目使用它时,TypeScript 能够正确地进行类型检查和推断。

为了让 TypeScript 能够识别“@vue/runtimecore” 模块中的类型信息,我们需要使用 declare module 语法来声明该模块。具体如下

// main.ts
// @vue/runtime-core
declare module '@vue/runtime-core' {
    // 在这里添加模块中的类型信息
    interface ComponentCustomProperties{
        $globalNum2:number
    }
}

这里需要getCurrentInstance()进行类型断言,还有对ComponentInternalInstance()进行类型约束,否则getCurrentInstance()函数上的proxy对象就会报错

// HelloWorld.vue
import type { ComponentInternalInstance } from 'vue'

 部分代码如下

// main.ts
import { createApp } from 'vue'
import './style.css'
import App from './HelloWorld.vue'

const app = createApp(App)
// @vue/runtime-core
declare module '@vue/runtime-core' {
    interface ComponentCustomProperties{
        $globalNum2:number
    }
}

app.mount('#app')
// HelloWorld.vue
<script setup lang="ts"&gt;
import _ from 'lodash'
import { getCurrentInstance } from 'vue'
import type { ComponentInternalInstance } from 'vue'

// console.log(globalNum);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
console.log(proxy?.$globalNum2);

globalFn();

console.log(globalFn.a);

// let arr = _.chunk([1,2,3])
// console.log(arr);

let array = [1];
let other = _.concat(array, 2, [3], [4])
console.log(other);
// [1,2,3,[4]]

console.log(array);
</script>

原文地址:https://blog.csdn.net/qq_53818683/article/details/129771072

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_36602.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注