vue3导入全局变量时,可以运行但是会一直显示报错,如图:
解决方法如下:
在 Vue.js 3 中,"@vue/runtime-core" 是一个包含 Vue.js 运行时核心的模块。这个模块提供了一些关键的 Vue.js 核心类型和方法,例如创建 Vue 实例、虚拟 DOM 渲染、组件渲染等等。当我们在 Vue.js 3 的项目中使用 TypeScript 进行编程时,我们需要使用"@vue/runtime-core" 模块来引入这些类型和方法。
在使用 TypeScript 编写 Vue.js 3 项目时,我们通常会使用 ".d.ts" 文件来描述 Vue.js 相关的类型信息。在这些文件中,我们需要声明"@vue/runtime-core" 模块的类型信息,以便在我们的项目中使用它时,TypeScript 能够正确地进行类型检查和推断。
为了让 TypeScript 能够识别"@vue/runtime-core" 模块中的类型信息,我们需要使用 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"> 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>
复制