Pinia基础使用 - 计数器案例
定义Store(state + action)
![](https://i-blog.csdnimg.cn/direct/99479f8731a94664844721843923e8c6.png)
组件使用Store
getters实现
Pinia中的 getters 直接使用 computed函数 进行模拟, 组件中需要使用需要把 getters return出去
action异步实现
编写方式:异步action函数的写法和组件中获取异步数据的写法完全一致接口地址:
需求:在Pinia中获取频道列表数据并把数据渲染App组件的模板中
storeToRefs工具函数
使用storeToRefs函数可以辅助保持数据(state + getter)的响应式解构
![](https://i-blog.csdnimg.cn/direct/7c872eade075441489d0628aba4a3806.png)
![](https://i-blog.csdnimg.cn/direct/8a91211a7f4449569bda1758691a33ec.png)
pinia持久化插件
![](https://i-blog.csdnimg.cn/direct/d4ad8ed9039846aebbbef8332a528a2e.png)
Pinia 如何快速实现持久化?
pinia-plugin-persistedstate
Vue3 大事件管理系统
创建项目
![](https://i-blog.csdnimg.cn/direct/90caa7d43c7b45f4942a5af09f4072d3.png)
-
进入项目目录
-
安装依赖
-
启动项目
Eslint 配置代码风格
配置文件 .eslintrc.cjs
-
prettier 风格配置
-
单引号
-
不使用分号
-
宽度80字符
-
不加对象|数组最后逗号
-
换行符号不限制(win mac 不一致)
-
vue组件名称多单词组成(忽略index.vue)
-
props解构(关闭)
注:安装Eslint且配置保存修复,不 要开启默认的自动保存格式化
![](https://i-blog.csdnimg.cn/direct/7a99b8d5403f4ce8a33c82562e4cbde2.png)
暂存区 eslint 校验
-
安装 lint-staged 包 pnpm i lint-staged -D
-
package.json 配置 lint-staged 命令
-
.husky/pre-commit 文件修改
![](https://i-blog.csdnimg.cn/direct/f4b0100db08e458988e296b1f416c1d5.png)
目录调整
默认生成的目录结构不满足我们的开发需求,所以这里需要做一些自定义改动。
主要是以下工作:
-
删除一些初始化的默认文件
-
修改剩余代码内容
-
新增调整我们需要的目录结构
-
拷贝全局样式和图片,安装预处理器支持
路由初始化
![](https://i-blog.csdnimg.cn/direct/40f208f1538448288c2b6b9b0b13b773.png)
![](https://i-blog.csdnimg.cn/direct/b6a059128a1b437eb26c56f6d5096aee.png)
创建路由实例由 createRouter 实现
路由模式
-
history 模式使用 createWebHistory()
-
hash 模式使用 createWebHashHistory()
-
参数是基础路径
![](https://i-blog.csdnimg.cn/direct/87c7029d0d824ee796e1a6a2a84a2128.png)
按需引入 Element Plus
Pinia 构建用户仓库 和 持久化
![](https://i-blog.csdnimg.cn/direct/0bf3221450534ad1a19ce9ab781b4acd.png)
Pinia 仓库统一管理
pinia 独立维护
初始化代码在 main.js 中,仓库代码在 stores 中,代码分散职能不单一
优化:由 stores 统一维护,在 stores/index.js 中完成 pinia 初始化,交付 main.js 使用
仓库 统一导出
使用一个仓库 import { useUserStore } from `./stores/user.js` 不同仓库路径不一致
优化:由 stores/index.js 统一导出,导入路径统一 `./stores`,而且仓库维护在 stores/modules 中
首页整体路由设计
![](https://i-blog.csdnimg.cn/direct/4bd0dbf0dbce4d58b8320e485241c00e.png)