pinia 的使用简要说明
语法(组合式)
——便于理解,可能会和选项式语法进行等价。
defineStore
1
2
3
4
5
6
7
8
9
export const <接口函数名> = defineStore('<唯一标识id>', () => { <详细定义> })
// 接口函数:在组件中调用它,就能拿到这个 store 的实例
// 唯一标识id:用来连接 store 和 devtools,在 devtools 或其他地方识别
// 注意 <详细定义> 处要用箭头函数
// 举例:
export const useAlertsStore = defineStore('alerts', {
// 其他配置...
})
详细定义-参数
- 响应式属性(对应
state):
1
2
3
4
5
6
const <属性名> = ref(<属性值>)
// 举例:
const count = ref(0)
const name = ref('Eduardo')
// 等价于 state: () => ({ count: 0, name: 'Eduardo' })
- 计算属性(对应
getters):
1
2
3
// computed()
// 举例:
const doubleCount = computed(() => count.value * 2)
- 函数方法(对应
actions)
1
2
3
4
5
// function()
// 举例:
function increment() {
count.value++
}
- return
要让 pinia 正确识别
state,你必须在 setup store 中返回state的所有属性。
1
...
功能分类
state:核心数据,store 对象的属性值。getters:只读取&处理(类似 Vue 的 computed)。actions:修改 state 的方法;同时可进行异步操作、业务逻辑处理 .etc。
本文由作者按照
CC BY 4.0
进行授权