美文网首页
【笔记】使用Vite搭建Vue3(TypeScript版本)项目

【笔记】使用Vite搭建Vue3(TypeScript版本)项目

作者: YoosonChan | 来源:发表于2022-01-17 19:01 被阅读0次

前提条件:

  1. 已安装nodejs环境(Tips:Vite 需要 Node.js 版本 >= 12.0.0)
  2. 已安装yarn

使用Vite搭建Vue的TypeScript版本的时候,可以使用Vite自带的模板预设——vue-ts

Tips:在Vue3的单文件组件(SFC)中,<script>已经很好的支持TypeScript,只需要把标签的lang属性设置为ts即可(<script lang="ts">...</script>(原文))。

1. 搭建Vue3(ts)基础环境

执行命令行

# npm 6.x
npm init vite@latest PROJECT_NAME --template vue-ts

# npm 7+, 需要额外的双横线:
npm init vite@latest PROJECT_NAME -- --template vue-ts

# yarn
yarn create vite PROJECT_NAME --template vue-ts

2. 安装Vue-Router

执行命令行(安装最新版本):

# npm
npm install vue-router@next
# yarn
yarn add vue-router@next

Tips:

  1. 在Vue3版本下,建议使用Vue-Router4原文)。
  2. 如需要自定义相应版本,将@后next改为对应版本号即可。

2.1 创建相应文件

router.ts

import { createRouter, createWebHistory } from 'vue-router'

export default createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      component: () => import('./views/Home.vue')
    },
    // ...其他路由配置
  ]
});

3. 安装Vuex

执行命令行(安装最新版本):

# npm
npm install vuex@next
# yarn
yarn add vuex@next

Tips:

  1. 在Vue3版本下,需要使用Vuex4才能够正常使用原文)。
  2. 如需要自定义相应版本,将@后next改为对应版本号即可。

3.1 创建相应文件:关于this.$store

Vuex 没有为 this.$store 属性提供开箱即用的类型声明。如果你要使用 TypeScript,首先需要声明自定义的模块补充(module augmentation)

为此,需要在项目文件夹中添加一个声明文件来声明 Vue 的自定义类型 ComponentCustomProperties

vuex.d.ts

// vuex.d.ts
import { ComponentCustomProperties } from 'vue'
import { Store } from 'vuex'

declare module '@vue/runtime-core' {
  // 声明自己的 store state
  interface State {
    count: number
  }

  // 为 `this.$store` 提供类型声明
  interface ComponentCustomProperties {
    $store: Store<State>
  }
}

当使用组合式 API 编写 Vue 组件时,您可能希望 useStore 返回类型化的 store。为了 useStore 能正确返回类型化的 store,必须执行以下步骤:

  1. 定义类型化的 InjectionKey
  2. 将 store 安装到 Vue 应用时提供类型化的 InjectionKey
  3. 将类型化的 InjectionKey 传给 useStore 方法。

store.ts

// store.ts
import { InjectionKey } from 'vue'
import { createStore, useStore as baseUseStore, Store } from 'vuex'

// 为 store state 声明类型
export interface State {
  count: number
}

// 定义 injection key
export const key: InjectionKey<Store<State>> = Symbol()

export const store = createStore<State>({
  state: {
    count: 0
  }
})

// 定义自己的 `useStore` 组合式函数
export function useStore() {
  return baseUseStore(key)
}

4. main.ts文件配置

main.ts

import { createApp } from 'vue'
import router from './router'
import { store, key } from './store'
import App from './App.vue'

const app = createApp(App)

app.use(router)
app.use(store, key)
app.mount('#app')

5. Vuex和Vue-Router的使用

main.ts已经声明配置过Vuex和Vue-Router之后,在<script setup lang="ts">或者<script lang="ts">中按需导入storerouter即可使用其属性和方法。

6. 补充

6.1 Vue-Router路由自动处理

参考:https://github.com/pohunchn/vite-ts-quick

router.ts

import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router"

function getRoutes() {
    const { routes } = loadRouters();
    /**
     * routes处理部分
     */
    return routes;
}

const router = createRouter({
    history: createWebHashHistory(),
    routes: getRoutes()
})

export default router;

/** 自动化处理view目录下的文件生成为路由 */
function loadRouters() {
    const context = import.meta.globEager("../views/**/*.vue");
    const routes: RouteRecordRaw[] = [];

    Object.keys(context).forEach((key: any) => {
        if (key === "./index.ts") return;
        let name = key.replace(/(\.\.\/views\/|\.vue)/g, '');
        let path = "/" + name.toLowerCase();
        if (name === "Index") path = "/";
        routes.push({
            path: path,
            name: name,
            component: () => import(`../views/${name}.vue`)
        })
    });

    return { context, routes }
}

7. 相关链接

  • 官方相关ts项目示例:vite-ts-quick - Vue 3 + Vuex + Vue-router + TypeScript Quick Template.
  • 官方相关项目示例:Awesome Vite.js

相关文章

网友评论

      本文标题:【笔记】使用Vite搭建Vue3(TypeScript版本)项目

      本文链接:https://www.haomeiwen.com/subject/hlkchrtx.html