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>

发表回复

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