Vue3 携手 TypeScript 搭建完整项目结构

yizhihongxing

一、准备工作
1. 安装 node.js(版本需大于等于 12.0.0) 和 npm(版本需大于等于 6.0.0);
2. 在终端中执行 npm install -g @vue/cli 安装 Vue CLI(版本需大于等于 4.5.0);
3. 在终端中执行 vue create my-project 创建一个 Vue 项目;
4. 在创建项目的时候,选择 Manually select features,然后选择 TypeScript、Router、Vuex、Linter / Formatter;
5. 等待项目的依赖安装完成后,在终端运行 npm run serve 启动项目。

二、Vue3 携手 TypeScript
1. 安装依赖:在终端中运行 npm install --save-dev vue@next @vue/compiler-sfc @vue/test-utils @types/node @types/vue @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint eslint-plugin-vue
2. 配置 TypeScript:在项目根目录创建 tsconfig.json 文件,并添加以下内容:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "strict": true,
    "jsx": "preserve",
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist", "test/"]
}
  1. 修改 main.ts:将 import Vue from 'vue' 修改为 import { createApp } from 'vue'Vue.config.productionTip = false 修改为 app.config.productionTip = falsenew Vue({ render: h => h(App) }).$mount('#app') 修改为 app.mount('#app')
  2. 修改样式文件(.css/.less/.scss):在样式文件最顶部添加 lang="scss"(示例为 Sass);
  3. 配置 webpack:在项目根目录创建 vue.config.js 文件,并添加以下内容:
module.exports = {
    chainWebpack: config => {
        // TypeScript Loader
        config.module
            .rule('typescript')
            .test(/\.ts$/)
            .use('babel-loader')
            .loader('babel-loader')
            .end()
            .use('ts-loader')
            .loader('ts-loader')
            .end()
            .include
            .add(/src/)
            .add(/test/)
            .end();
    }
};
  1. 创建组件:在 src/components 目录下创建一个名为 HelloWorld.vue 的组件,并添加以下内容:
<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'HelloWorld',
  props: {
    msg: String
  }
});
</script>

<style lang="scss">
.hello {
  h1 {
    font-size: 36px;
  }
}
</style>
  1. 修改 App.vue:在 Vue3.x 中,需要在主组件中使用 defineComponent 定义父组件。修改 src/App.vue 文件,并添加 HelloWorld 组件:
<template>
  <div id="app">
    <HelloWorld msg="Welcome to Your Vue.js + TypeScript App"/>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import HelloWorld from './components/HelloWorld.vue';

export default defineComponent({
  name: 'App',
  components: {
    HelloWorld
  }
})
</script>
  1. 验证效果:在终端中运行 npm run serve,在浏览器中查看项目是否正常运行。

三、搭建完整项目结构
1. 目录结构参考:

my-project/
├── node_modules/
├── public/
├── src/
│   ├── api/
│   │   └── index.ts            // 接口请求工具的定义
│   ├── assets/
│   │   ├── logo.png
│   │   └── ...
│   ├── components/
│   │   └── HelloWorld.vue
│   ├── router/
│   │   └── index.ts            // 路由配置
│   ├── store/
│   │   ├── index.ts            // Vuex store 的定义
│   │   ├── actions.ts
│   │   ├── mutations.ts
│   │   ├── getters.ts
│   │   └── modules/
│   ├── utils/
│   │   ├── index.ts            // 工具函数
│   │   └── ...
│   ├── views/
│   │   ├── Home.vue
│   │   └── ...
│   ├── App.vue
│   └── main.ts
├── tests/
│   ├── e2e/
│   └── unit/
├── .eslintrc.js
├── babel.config.js
├── package-lock.json
├── package.json
└── tsconfig.json
  1. 编写接口请求工具:在 src/api 目录下创建 index.ts 文件,并添加以下内容:
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';

interface RequestOptions extends AxiosRequestConfig {}

interface RequestPromise extends Promise<AxiosResponse<any>> {}

export class Http {
  private static DEFAULT_TIMEOUT = 10000;
  private $http: AxiosInstance;
  private static instance: Http;

  private constructor(config: RequestOptions) {
    this.$http = axios.create(config);
  }

  public static getInstance(config: RequestOptions): Http {
    if (!this.instance) {
      this.instance = new Http({
        timeout: Http.DEFAULT_TIMEOUT,
        ...config
      });
    }
    return this.instance;
  }

  public request(options: RequestOptions) {
    const instance = this.$http;
    return instance(options) as RequestPromise;
  }
}

export const http = Http.getInstance({
  baseURL: 'https://jsonplaceholder.typicode.com/'
});
  1. 配置路由:在 src/router 目录下创建 index.ts 文件,并添加以下内容:
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import Home from '../views/Home.vue';

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});

export default router;
  1. 创建 Vuex store:在 src/store 目录下创建 index.ts 文件,并添加以下内容:
import { createStore } from 'vuex';
import { actions } from './actions';
import { mutations } from './mutations';
import { getters } from './getters';
import { moduleA } from './modules/moduleA';

export default createStore({
  state: {
    count: 0
  },
  mutations,
  actions,
  getters,
  modules: {
    moduleA
  }
});
  1. src/main.ts 中引入路由和 Vuex:在 main.ts 文件中,引入 Router 和 Vuex :
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';

const app = createApp(App);
app.use(router);
app.use(store);
app.mount('#app');
  1. 测试:在浏览器中打开 http://localhost:8080,路由和 Vuex 是否正常运行。

至此,我们就完成了将 Vue 3.x 搭建 TypeScript 环境、搭建完整项目结构的攻略。

示例说明:
1. 在接口请求工具之中,使用 class 和 interface 进行封装,并在外部调用时使用单例的模式返回实例,避免了频繁创建的问题;
2. 在模块化 Vuex store 的过程中,我们使用模块化的方式对 store 进行分层。在 moduleA.ts 文件中,我们看到除了 state、mutations、actions、getters 之外,还会有子模块 children,以此来进行更加细致和完善的 store 管理。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Vue3 携手 TypeScript 搭建完整项目结构 - Python技术站

(0)
上一篇 2023年6月10日
下一篇 2023年6月10日

相关文章

  • jquery实现类似EasyUI的页面布局可改变左右的宽度

    实现类似EasyUI的页面布局可改变左右的宽度,可以通过使用jQuery UI中的resizable方法来实现。 步骤一:准备布局 首先,需要准备好需要添加布局的HTML代码,一般采用一定的CSS样式进行控制。例如,需要添加左右两个区域,可以通过如下代码实现: <div class="layout"> <div clas…

    css 2023年6月11日
    00
  • 详解CSS3中强大的filter(滤镜)属性

    下面是详解CSS3中强大的filter(滤镜)属性的完整攻略。 什么是CSS3 filter属性? CSS3 filter属性是一种用于样式表中的图像滤镜。该属性可用于创建许多不同的视觉效果和处理图像。从模糊、变灰、色调、对比度等功能,到影像转换的效果,都可以使用CSS3 filter属性来实现。 CSS3 filter的语法 CSS3 filter属性有一…

    css 2023年6月10日
    00
  • javascript基本数据类型和转换

    JavaScript基本数据类型和转换 JavaScript是一种弱类型语言,数据类型是JavaScript编程中非常重要的一个概念。在JavaScript中,有基本数据类型和复杂数据类型。接下来将会详细地讲解基本数据类型和它们之间的转换。 基本数据类型 JavaScript中有6种基本数据类型:字符串(string)、数值(number)、布尔值(bool…

    css 2023年6月9日
    00
  • Vue前端项目自适应布局的简单方法

    我来详细讲解一下“Vue前端项目自适应布局的简单方法”的完整攻略。 目录 背景介绍 解决方案 使用vw单位 使用flex布局 示例说明 示例1:使用vw单位 示例2:使用flex布局 总结 背景介绍 随着移动端设备的普及,越来越多的网站需要进行自适应布局,以适应不同的屏幕尺寸,保证用户体验。Vue前端项目也不例外。但是,对于一些初学者来说,很难在Vue项目中…

    css 2023年6月9日
    00
  • ReactJs设置css样式的方法

    ReactJs 中设置 CSS 样式有多种方法,下面将介绍几种常用的方法: 1. 内联样式 在 ReactJs 中,可以使用内联样式设置组件的样式。内联样式以对象形式定义,对象中的属性名必须为 camelCase 风格的字符串,而属性值则是字符串或者数字。 示例: import React from ‘react’; const MyComponent = …

    css 2023年6月9日
    00
  • 深入解析CSS中的自定义属性

    深入解析CSS中的自定义属性,以下是完整攻略: 什么是自定义属性 自定义属性(Custom Properties),又称变量(Variables)。它是CSS新增的一项功能,用于保存一个值,然后可以在整个文档中随时调用它。解析时会替换为具体的值。 自定义属性可以使用–开头的名称声明,如: :root{ –main-color: #333; } 这个样式表…

    css 2023年6月9日
    00
  • 关于CSS中定位的小结

    好的。首先,我们要明确CSS中定位的基础知识。在CSS中,有三种常见的定位方式:静态定位(static)、相对定位(relative)和绝对定位(absolute)。其中,静态定位是默认的定位方式,元素在页面上按照它们在HTML中出现的顺序依次排列,不受其他元素的影响。相对定位和绝对定位则可以让元素脱离文档流,可以更灵活地排列和布局。 下面是具体的攻略: 1…

    css 2023年6月9日
    00
  • 如何换个角度使用VUE过滤器详解

    下面就是关于如何换个角度使用VUE过滤器的完整攻略了。 什么是VUE过滤器? VUE过滤器是一种用于格式化显示内容的机制,在VUE中使用{{ }}语法进行内容绑定时,可以通过管道符“|”来使用过滤器。例如:{{msg | capitalize}}。在这个例子中,capitalize就是一个过滤器。 如何使用VUE过滤器? 在Vue的template模板中使用…

    css 2023年6月10日
    00
合作推广
合作推广
分享本页
返回顶部