<think>由于问题涉及多个技术栈,我们将分步骤搭建项目。这里将详细说明如何使用Vue3、Vue Router、Pinia、Eslint、TypeScript以及Pinia持久化来搭建一个项目。
步骤:
1. 创建Vue3项目(使用Vite)
2. 安装Vue Router
3. 安装Pinia和持久化插件
4. 配置TypeScript
5. 配置Eslint
6. 项目结构组织
### 1. 创建Vue3项目
使用Vite创建Vue3项目,选择TypeScript模板。
```bash
npm create vite@latest my-vue-app -- --template vue-ts
cd my-vue-app
npm install
```
### 2. 安装Vue Router
```bash
npm install vue-router@4
```
创建路由配置文件:在`src`目录下创建`router`文件夹,然后创建`index.ts`文件。
```typescript
// src/router/index.ts
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Home',
component: () => import('@/views/Home.vue') // 需要创建Home视图
},
// 其他路由...
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
```
在`main.ts`中引入路由:
```typescript
// src/main.ts
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')
```
### 3. 安装Pinia和持久化插件
```bash
npm install pinia
npm install pinia-plugin-persistedstate
```
创建Pinia实例并应用持久化插件:
```typescript
// src/store/index.ts
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
export default pinia
```
在`main.ts`中使用Pinia:
```typescript
// src/main.ts
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import pinia from './store'
createApp(App).use(router).use(pinia).mount('#app')
```
创建一个store示例(例如用户store):
```typescript
// src/store/user.ts
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state: () => ({
name: 'John Doe',
age: 30,
}),
actions: {
updateName(name: string) {
this.name = name
},
},
persist: true // 开启持久化
})
```
### 4. 配置TypeScript
Vite创建的Vue3项目已经自带了TypeScript,我们只需要确保`tsconfig.json`配置正确。可以根据需要调整配置。
### 5. 配置Eslint
安装Eslint及相关插件:
```bash
npm install eslint eslint-plugin-vue @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev
```
创建`.eslintrc.js`文件:
```javascript
module.exports = {
env: {
browser: true,
es2021: true,
node: true,
},
extends: [
'eslint:recommended',
'plugin:vue/vue3-recommended',
'plugin:@typescript-eslint/recommended',
],
parser: 'vue-eslint-parser',
parserOptions: {
ecmaVersion: 'latest',
parser: '@typescript-eslint/parser',
sourceType: 'module',
},
plugins: ['vue', '@typescript-eslint'],
rules: {
// 自定义规则
'vue/multi-word-component-names': 'off', // 关闭组件名必须多单词的限制
},
}
```
在`package.json`中添加lint脚本:
```json
"scripts": {
"lint": "eslint . --ext .vue,.ts,.tsx --fix"
}
```
### 6. 项目结构
建议项目结构如下:
```
src/
├── assets/
├── components/
├── views/
│ ├── Home.vue
│ └── ...
├── router/
│ └── index.ts
├── store/
│ ├── index.ts
│ └── user.ts
├── App.vue
└── main.ts
```
### 示例代码
这里给出一个简单的`Home.vue`示例,展示如何使用Pinia store:
```vue
<template>
<div>
<h1>Home Page</h1>
<p>User: {{ userStore.name }}</p>
<button @click="changeName">Change Name</button>
</div>
</template>
<script setup lang="ts">
import { useUserStore } from '@/store/user'
const userStore = useUserStore()
const changeName = () => {
userStore.updateName('Jane Doe')
}
</script>
```
### 解释
- 使用Vite创建项目,速度快且配置简单。
- Vue Router用于路由管理,采用历史模式。
- Pinia作为状态管理库,替代Vuex,更轻量且支持Composition API。
- Pinia持久化插件`pinia-plugin-persistedstate`可以将store的状态持久化到localStorage或sessionStorage。
- TypeScript提供类型支持,减少错误。
- Eslint统一代码风格,提高代码质量。
### 注意事项
- 持久化配置:在store定义中设置`persist: true`即可开启,也可以配置详细选项(如存储方式、key等)。
- 路由懒加载:使用`() => import('...')`实现懒加载,优化首屏加载速度。
§§相关问题§§:
1. 如何在Vue Router中配置动态路由?
2. Pinia持久化可以存储到cookie吗?如何配置?
3. 如何配置Eslint和Prettier一起工作?
4. 在TypeScript中如何为Vue组件定义Props的类型?</think>下面我将详细介绍如何使用 Vue 3 + Vue Router + Pinia + ESLint + TypeScript + Pinia 持久化搭建项目,并提供完整的代码示例和解释。
### 完整项目搭建指南
#### 1. 创建项目(使用 Vite)
```bash
npm create vite@latest my-vue-app -- --template vue-ts
cd my-vue-app
npm install
```
#### 2. 安装必要依赖
```bash
npm install vue-router@4 pinia pinia-plugin-persistedstate
npm install -D eslint eslint-plugin-vue @typescript-eslint/parser @typescript-eslint/eslint-plugin
```
#### 3. 项目结构
```markdown
src/
├── assets/
├── components/
├── router/
│ └── index.ts
├── store/
│ ├── index.ts
│ └── userStore.ts
├── views/
│ ├── Home.vue
│ └── About.vue
├── App.vue
├── main.ts
.eslintrc.cjs
```
#### 4. 配置 Vue Router
```typescript
// src/router/index.ts
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
```
#### 5. 配置 Pinia 和持久化
```typescript
// src/store/index.ts
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
export default pinia
```
```typescript
// src/store/userStore.ts
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state: () => ({
name: 'John',
age: 30,
preferences: {
theme: 'dark',
notifications: true
}
}),
actions: {
updateName(newName: string) {
this.name = newName
}
},
persist: {
paths: ['name', 'preferences.theme'], // 指定持久化字段
storage: localStorage // 默认使用 localStorage
}
})
```
#### 6. 配置 ESLint
```javascript
// .eslintrc.cjs
module.exports = {
env: { browser: true, es2021: true },
extends: [
'eslint:recommended',
'plugin:vue/vue3-recommended',
'plugin:@typescript-eslint/recommended'
],
parser: 'vue-eslint-parser',
parserOptions: {
parser: '@typescript-eslint/parser',
ecmaVersion: 'latest',
sourceType: 'module'
},
plugins: ['vue', '@typescript-eslint'],
rules: {
'vue/multi-word-component-names': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'vue/html-self-closing': ['error', {
html: {
void: 'always',
normal: 'never',
component: 'always'
}
}]
}
}
```
#### 7. 配置 main.ts
```typescript
// src/main.ts
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import pinia from './store'
const app = createApp(App)
app.use(router)
app.use(pinia)
app.mount('#app')
```
#### 8. 示例组件使用
```vue
<!-- src/views/Home.vue -->
<script setup lang="ts">
import { useUserStore } from '@/store/userStore'
const userStore = useUserStore()
</script>
<template>
<div>
<h1>Home Page</h1>
<p>User: {{ userStore.name }}</p>
<input v-model="userStore.name" />
<p>Theme: {{ userStore.preferences.theme }}</p>
</div>
</template>
```
#### 9. 配置 package.json 脚本
```json
{
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build",
"lint": "eslint . --ext .vue,.ts,.tsx --fix",
"preview": "vite preview"
}
}
```
### 关键配置解释
1. **Pinia 持久化**:
- 使用 `pinia-plugin-persistedstate` 插件
- 在 store 定义中添加 `persist` 配置
- `paths` 可指定需要持久化的具体字段
- 默认使用 localStorage,可替换为 sessionStorage
2. **ESLint 配置**:
- 使用 Vue3 推荐规则 + TypeScript 规则
- 关闭多单词组件名限制(开发时可开启)
- 配置 Vue/HTML 自闭合标签规则
3. **TypeScript 支持**:
- Vite 默认提供 Vue+TS 模板
- 组件中使用 `<script setup lang="ts">` 语法
- 为 Pinia store 提供完整的类型推断
4. **路由配置**:
- 使用 createWebHistory 实现 SPA 路由
- 组件使用懒加载(示例中为静态引入)
### 运行项目
```bash
npm run dev
npm run lint # 检查代码规范
```
### 持久化效果验证
1. 在页面修改用户名
2. 刷新页面后数据保持不变
3. 检查 localStorage 中的 `pinia.user` 值