学习pinia day1

74 阅读1分钟

1.pinia是什么?

pinia是一个具有组合式API的vue状态管理库。
2.为何选择pinia?

  1. pinia 组合式API,跟vue3比较搭配
  2. 仍更新,不必重载页面即可更新store
  3. 插件,通过插件补充功能
  4. 提供typescript支持以及提供补全功能

3.如何实现一个pinia?

defineStore() 传入两个参数, id,setup函数或者对象

export const useAlertsStore = defineStore('alerts', { // 其他配置... })

可以使用选项式API或者组合式API,以下例子是组合式API

export const useCounterStore = defineStore('counter', () => { const count = ref(0) function increment() { count.value++ } return { count, increment } })

ref就是state属性,computed是getters,function就是actions

少了一个mutation,mutation必须是同步操作

3.深入理解篇

  1. pinia中访问state: js const store=useStore() state.count
  • 不能使用结构解析,会失去响应性,可以使用storeToRefs再结构解析
  1. 更新state js store.$pacth({age:20,name:'wjy'}) 当变更很难实现或者很耗时时候,支持通过函数实现。 store.$patch((state)=>{ state.items.push({ name: 'shoes', quantity: 1 }) })

3.替换state时候,不应该使用store.state={} 应该使用 store.$patch({count:25})