【超详细】vue3+pinia+自动持久化插件+自定义存储器对象实现状态数据持久化

    本文超详细讲解了 vue3+pinia+自动持久化插件+自定义存储器对象实现状态数据持久化 的配置和代码实现,会不会详细得令人发指😄😄😄!
 之前在 vue2 版本中,普遍都是使用 vuex 插件和手写操作 localStorage 或 sessionStorage 的 actions 方法对应用中组件间的共享数据(状态)进行管理。
 由于 vuex 比较臃肿,并且对 TS 支持不够好,vue3 中改为普遍使用 pinia 这个轻量级的状态数据管理插件,该插件也是官方在 vuex 的基础进行优化和修改的,区别是更轻量,性能更好,对 TS 语法的支持较好,并且去除了多余的 Mutations 配置项,直接例用 actions 配置项配置操作 state 数据的方法即可!
 例用 pinia 插件 + 数据持久化插件 pinia-plugin-persistedstate,可以在应用运行中自动持久化 pinia store state 中的数据到浏览器自带本地存储 window.localStorage 和 window.sessionStorage (这两个本地存储器是数据持久化插件 pinia-plugin-persistedstate默认自带支持的),及支持自定义存储器对象,比如本例自定义了一个 cookie 的存储器对象 cookieStorage。
 话不多说,直接入正题!

以下是配置部分:
1、安装所需插件包:pinia、pinia-plugin-persistedstate、js-cookie
npm i pinia pinia-plugin-persistedstate js-cookie
2、在 ./src/store 目录下创建 cookieStorage.js 存储器对象:
// cookieStorage.js
/**
 *  为 pinia-plugin-persistedstate 插件自定义 storage 存储器对象 cookieStorage,
 *  自定义存储器对象,必须按以下要求实现 setItem 和 getItem 方法,并且在这两个方法调用设置/读取 cookie 等
 *  本地存储的方法必须是同步的,不能是异步的,
 *  这里使用 js-cookie 第三方 cookie 操作包实现自定义 storage 存储器对象 cookieStorage
 */
import Cookie from 'js-cookie'

export const cookieStorage = {
   
   
    // 参数 key 为 userStore.js 中 persist 配置项中保存到 storage 存储中的 key 键名
    // 参数 state 为 userStore.js 中 persist 配置项中要持久化到 storage 的 state 属性名,不是全部 state
    setItem(key, state) {
   
   
        // console.log('cookieStorage setItem state:', state)
        // js-cookie 包 setItem 方法的第三个参数配置对象解释:
        // expires: 为数字时表示过期天数,缺少该参数,表示仅会话期间有效,支持 new Date 对象及其字符串格式
        // path:默认值为/,表示全站点所有路径页面可操作该 cookie,为 '' 空值表示仅当前页面可操作该 cookie
        // domain:缺省该参数默认值为当前域名及其子域名可操作该 cookie
        // return Cookie.setItem(key, state, { expires: 9999, path: '/', domain: '' })
        return Cookie.set(key, state)

    },
    getItem(key) {
   
     // 首次自动加载这个自定义cookie存储器时, getItem 方法比 setItem 方法先执行
        // console.log('cookieStorage getItem:', key, Cookie.get(key))
        let value = Cookie.get(key) || '{}'
<think>由于问题涉及多个技术栈,我们将分步骤搭建项目。这里将详细说明如何使用Vue3Vue 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 &#39;vue-router&#39; const routes: Array<RouteRecordRaw> = [ { path: &#39;/&#39;, name: &#39;Home&#39;, component: () => import(&#39;@/views/Home.vue&#39;) // 需要创建Home视图 }, // 其他路由... ] const router = createRouter({ history: createWebHistory(), routes }) export default router ``` 在`main.ts`中引入路由: ```typescript // src/main.ts import { createApp } from &#39;vue&#39; import App from &#39;./App.vue&#39; import router from &#39;./router&#39; createApp(App).use(router).mount(&#39;#app&#39;) ``` ### 3. 安装Pinia持久化插件 ```bash npm install pinia npm install pinia-plugin-persistedstate ``` 创建Pinia实例并应用持久化插件: ```typescript // src/store/index.ts import { createPinia } from &#39;pinia&#39; import piniaPluginPersistedstate from &#39;pinia-plugin-persistedstate&#39; const pinia = createPinia() pinia.use(piniaPluginPersistedstate) export default pinia ``` 在`main.ts`中使用Pinia: ```typescript // src/main.ts import { createApp } from &#39;vue&#39; import App from &#39;./App.vue&#39; import router from &#39;./router&#39; import pinia from &#39;./store&#39; createApp(App).use(router).use(pinia).mount(&#39;#app&#39;) ``` 创建一个store示例(例如用户store): ```typescript // src/store/user.ts import { defineStore } from &#39;pinia&#39; export const useUserStore = defineStore(&#39;user&#39;, { state: () => ({ name: &#39;John Doe&#39;, 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: [ &#39;eslint:recommended&#39;, &#39;plugin:vue/vue3-recommended&#39;, &#39;plugin:@typescript-eslint/recommended&#39;, ], parser: &#39;vue-eslint-parser&#39;, parserOptions: { ecmaVersion: &#39;latest&#39;, parser: &#39;@typescript-eslint/parser&#39;, sourceType: &#39;module&#39;, }, plugins: [&#39;vue&#39;, &#39;@typescript-eslint&#39;], rules: { // 自定义规则 &#39;vue/multi-word-component-names&#39;: &#39;off&#39;, // 关闭组件名必须多单词的限制 }, } ``` 在`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 &#39;@/store/user&#39; const userStore = useUserStore() const changeName = () => { userStore.updateName(&#39;Jane Doe&#39;) } </script> ``` ### 解释 - 使用Vite创建项目,速度快且配置简单。 - Vue Router用于路由管理,采用历史模式。 - Pinia作为状态管理库,替代Vuex,更轻量且支持Composition API。 - Pinia持久化插件`pinia-plugin-persistedstate`可以将store的状态持久化到localStorage或sessionStorage。 - TypeScript提供类型支持,减少错误。 - Eslint统一代码风格,提高代码质量。 ### 注意事项 - 持久化配置:在store定义中设置`persist: true`即可开启,也可以配置详细选项(如存储方式、key等)。 - 路由懒加载:使用`() => import(&#39;...&#39;)`实现懒加载,优化首屏加载速度。 §§相关问题§§: 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 &#39;vue-router&#39; import Home from &#39;../views/Home.vue&#39; import About from &#39;../views/About.vue&#39; const routes = [ { path: &#39;/&#39;, component: Home }, { path: &#39;/about&#39;, component: About } ] const router = createRouter({ history: createWebHistory(), routes }) export default router ``` #### 5. 配置 Pinia持久化 ```typescript // src/store/index.ts import { createPinia } from &#39;pinia&#39; import piniaPluginPersistedstate from &#39;pinia-plugin-persistedstate&#39; const pinia = createPinia() pinia.use(piniaPluginPersistedstate) export default pinia ``` ```typescript // src/store/userStore.ts import { defineStore } from &#39;pinia&#39; export const useUserStore = defineStore(&#39;user&#39;, { state: () => ({ name: &#39;John&#39;, age: 30, preferences: { theme: &#39;dark&#39;, notifications: true } }), actions: { updateName(newName: string) { this.name = newName } }, persist: { paths: [&#39;name&#39;, &#39;preferences.theme&#39;], // 指定持久化字段 storage: localStorage // 默认使用 localStorage } }) ``` #### 6. 配置 ESLint ```javascript // .eslintrc.cjs module.exports = { env: { browser: true, es2021: true }, extends: [ &#39;eslint:recommended&#39;, &#39;plugin:vue/vue3-recommended&#39;, &#39;plugin:@typescript-eslint/recommended&#39; ], parser: &#39;vue-eslint-parser&#39;, parserOptions: { parser: &#39;@typescript-eslint/parser&#39;, ecmaVersion: &#39;latest&#39;, sourceType: &#39;module&#39; }, plugins: [&#39;vue&#39;, &#39;@typescript-eslint&#39;], rules: { &#39;vue/multi-word-component-names&#39;: &#39;off&#39;, &#39;@typescript-eslint/no-explicit-any&#39;: &#39;off&#39;, &#39;vue/html-self-closing&#39;: [&#39;error&#39;, { html: { void: &#39;always&#39;, normal: &#39;never&#39;, component: &#39;always&#39; } }] } } ``` #### 7. 配置 main.ts ```typescript // src/main.ts import { createApp } from &#39;vue&#39; import App from &#39;./App.vue&#39; import router from &#39;./router&#39; import pinia from &#39;./store&#39; const app = createApp(App) app.use(router) app.use(pinia) app.mount(&#39;#app&#39;) ``` #### 8. 示例组件使用 ```vue <!-- src/views/Home.vue --> <script setup lang="ts"> import { useUserStore } from &#39;@/store/userStore&#39; 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` 值
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值