(syntax)pinia
2022-10-13 00:00:00
pinia
piniaApi
pinia vs vuex
- 抛弃传统的
Mutation,只有state, getter和action,简化状态管理库- 不需要嵌套模块,符合 Vue3 的 Composition api,让代码扁平化
- TS支持
- 代码自动分割
- 小 1K
store 仓库
- state 数据
- 定义
export const mainStore = defineStore('main',{ state:{} })- 使用
const store = mainStore()const { name } = storeToRefs(store)- 组件 store.name name
- 修改
store.属性名单个数据修改store.$path多个数据修改(类似辅助函数)
$path((state)=>{ })+$path({})- getters 计算
- 定义
export const mainStore = definStore('main',{ getters:{} })- 使用 导入 + 文件名() +
store.getters名- actions 方法
- 定义
export const mainStore = definStore('main',{ actions:{} })- 使用 导入 + 文件名() + store.action方法()
- store 文件分割
1 | |
1 | |
state数据
- 定义
export const mainStore = defineStore('main',{ state:()=>{} })- 使用
const store = mainStore()const { name } = storeToRefs(store)- 修改
store.属性名单个数据修改store.$path多个数据修改(类似辅助函数)
store.$path((state)=>{ })+store.$path({})
定义
1 | |
使用(解构store)
1 | |
修改
store.属性名单个数据修改store.$path多个数据修改(类似辅助函数)$path((state)=>{ })+$path({})
1 | |
getters计算
- 定义
export const mainStore = definStore('main',{ getters:{} })- 使用 导入 + 文件名() +
store.getters名
- 与vue的计算属性集合一样 有缓存 值没有改变多次调用同一个
定义
1 | |
使用
1 | |
actions方法
- 定义
export const mainStore = definStore('main',{ actions:{} })- 使用 store.action方法()
定义
1 | |
- 使用
1 | |
store仓库
- 分离store文件
- 使用 导入 + 文件().xxx //
1 | |