在 vue 中使用 typescript 步驟:安裝 typescript 和相關(guān)支持包。創(chuàng)建 tsconfig.json 文件配置 typescript 編譯器。在 vue.config.JS 中添加 typescript 支持。創(chuàng)建包含 typescript 代碼的 vue 組件。啟用 typescript 類型檢查。可選:使用 vue-class-component 庫簡化 typescript 組件編寫。探索 typescript 的其他功能,如類型別名、接口和泛型。
如何在 Vue 中使用 TypeScript
引入 TypeScript
要在 Vue 項目中使用 TypeScript,需要安裝 TypeScript 和相應(yīng)的支持包:
npm install typescript @vue/cli-plugin-typescript
創(chuàng)建 TypeScript 配置文件
創(chuàng)建 tsconfig.json 文件以配置 TypeScript 編譯器:
{ "compilerOptions": { "target": "es2020", "module": "es2015", "lib": ["es2020", "dom"], "sourceMap": true } }
添加 TypeScript 語言支持
在 vue.config.js 文件中添加 TypeScript 支持:
module.exports = { // ... transpileDependencies: [ // ... 'vue-router', // 添加 Vue Router 支持 ], };
創(chuàng)建 TypeScript 組件
編寫一個名為 MyComponent.vue 的 TypeScript 組件:
立即學(xué)習(xí)“前端免費學(xué)習(xí)筆記(深入)”;
<template> <div>My Component</div> </template> <script lang="ts"> import { Vue, Component, Prop } from 'vue-property-decorator'; @Component export default class MyComponent extends Vue { @Prop() public name?: string; } </script>
啟用 TypeScript 類型檢查
TypeScript 會自動類型檢查您的組件。如果您遇到類型錯誤,將顯示錯誤消息。
使用 vue-class-component
vue-class-component 是一個庫,它允許您使用 TypeScript 的類語法來編寫 Vue 組件。要使用它,需要安裝它:
npm install vue-class-component
然后,您可以在 TypeScript 組件中使用它:
@Component export default class MyComponent extends Vue { // ... }
使用其他 TypeScript 功能
TypeScript 允許您使用各種其他功能,例如:
有關(guān)更多詳細信息,請參閱 TypeScript 文檔。