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

前提条件:

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

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

Tips:在Vue3的单文件组件(SFC)中,(原文))。

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
  }
}

当使用组合式 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> = Symbol()

export const store = createStore({
  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之后,在

你可能感兴趣的:(【笔记】使用Vite搭建Vue3(TypeScript版本)项目)