1. 首页

带你初探 Vue3 + TS

带你初探 Vue3 + TS

编译没问题但报红

  • 用 vue-cli 创建的项目在 WebStorm 中 main.ts 可能会有如下情况。 带你初探 Vue3 + TS 原因是 App 不是 Component,解决方法如下:
 ts
    // App.vue
    <script lang="ts">
      import { defineComponent } from 'vue';
      export default defineComponent({});
    </script>
    ```
> Js中文网 - 前端进阶资源教程 [www.javascriptC.com](https://www.javascriptc.com),typescript 中文文档
> 一个帮助开发者成长的社区,**你想要的,在这里都能找到**


+   在 router/index.js 中可能会有如下情况 ![](https://static.javascriptc.com/frontend/vue/20201015/vue3-p-zoom-1cddab630.image) 原因是 App 不是 Component,解决方法如下:


```javascript
 ts
    // router/index.vue
    const routes: Array<RouteRecordRaw> = [
      {
        path: '/',
        name: 'Home',
        component: () => Home
      },
      {
        path: '/about',
        name: 'About',
        component: () => import('../views/About.vue')
      }
    ]
    ```



## 全局实例定义

在 Vue2 中定义全局实例的方式


```javascript
import Utils from './libs/utils'
...
Vue.prototype.$utils = Utils

但到了 Vue3 中不适用 Vue2 的方法定义全局实例,而且还报错。

Vue3 定义全局实例有两种写法:

  • 第一种写法
 ts
// libs/utils.ts
import { App } from 'vue';

declare interface Utils {
  addN(n: number): number;
}

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $utils: Utils;
  }
}

export default {
  install(app: App) {
    app.config.globalProperties.$utils = {
      addN(n: number): number {
        return n == 1 ? 1 : n + this.addN(n - 1);
      }
    }
  }
}
 ts
// main.ts
import Utils from './libs/utils';
...
const app = createApp(App);
app.use(Utils);
...
app.mount('#app');
  • 第二种写法

Js中文网 – 前端进阶资源教程 www.javascriptC.com,typescript 中文文档
一个帮助开发者成长的社区,你想要的,在这里都能找到

 ts
// libs/utils.ts
declare interface Utils {
  addN(n: number): number;
}

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $utils: Utils;
  }
}

export default {
  addN(n: number): number {
    return n == 1 ? 1 : n + this.addN(n - 1);
  }
}
 ts
import Utils from './libs/utils';
...
app.config.globalProperties.$utils = Utils;
...
app.mount('#app');

两种写法都有一段代码是相同的,就是

 ts
// libs/utils.ts
declare interface Utils {
  addN(n: number): number;
}

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $utils: Utils;
  }
}

如果没了这段代码编译会报错 带你初探 Vue3 + TS 加上之后需要重启,否则还是报这个错误。

在 @vue/runtime-core 中作者其实已经写了一个例子:
带你初探 Vue3 + TS

作者:大肥肥喵
链接:https://juejin.im/post/6881464786400477198

看完两件小事

如果你觉得这篇文章对你挺有启发,我想请你帮我两个小忙:

  1. 关注我们的 GitHub 博客,让我们成为长期关系
  2. 把这篇文章分享给你的朋友 / 交流群,让更多的人看到,一起进步,一起成长!
  3. 关注公众号 「画漫画的程序员」,公众号后台回复「资源」 免费领取我精心整理的前端进阶资源教程

JS中文网是中国领先的新一代开发者社区和专业的技术媒体,一个帮助开发者成长的社区,目前已经覆盖和服务了超过 300 万开发者,你每天都可以在这里找到技术世界的头条内容。欢迎热爱技术的你一起加入交流与学习,JS中文网的使命是帮助开发者用代码改变世界

本文著作权归作者所有,如若转载,请注明出处

转载请注明:文章转载自「 Js中文网 · 前端进阶资源教程 」https://www.javascriptc.com

标题:带你初探 Vue3 + TS

链接:https://www.javascriptc.com/4117.html

« 那些年与面试官交手过的HTTP问题
web Nginx 初探»
Flutter 中文教程资源

相关推荐

QR code