pinia是什么? vue的储存库,允许跨组件/页面共享状态
pinia用在什么场景?
- 存储应该包含在整个应用程序中访问的数据,例如导航栏中显示的用户信息,以及需要通过页面保留的数据。
- 兄弟组件进行通信,场景举例: 比如A组件和B组件是兄弟组件,A组件改变后,B组件需要知道,不使用pinia的话可以先通知父组件,由父组件再通知B组件,这样感觉不优雅,这时pinia就可以发挥作用了,可以定义一个store,然后A去修改store,B订阅store便可实现
store
一个 Store是一个实体,【官网:它持有未绑定到您的组件树的状态和业务逻辑,托管全局状态,可以把它理解成一个始终存在并且每个人都可以读取和写入的组件】。简单来说,我们可以当成一个处在顶级的共享组件,它有三个概念,state、getters 和 actions 可以假设这些概念等同于组件中的“数据”、“计算属性”和“方法”。
定义方式:counter.ts
export const useCounterStore = defineStore('counter',() => { // 第一个参数需唯一
const count ref(0) // state
const increment=()=>{ // action
count.value++
}
const doubleCount =computed(()=>count.value*2) // getters
return {count,increment,doubleCount} // 返回
})
A组件中使用:
const counter = useCounterStore()
const addCounter = () => {
counter.increment()
}
A组件执行一次后,去B组件便可以拿到最新的count值
const counter = useCounterStore()
console.log(counter.counter) // 1
console.log(counter.doubleCount) // 2
若要实时知道改变,则可以在B订阅
const counter = useCounterStore()
counter.$subscribe((mutation, state) => {
console.log('改变了', state)
})
以上是pinia的使用方法, 此外针对state、getters、action还有些别的api,下面分别介绍下,下面涉及到的 store = useCounterStore()
state
- 访问state: store.属性
- 重置state: store.$reset()
- 修改state: store.属性 = 'xxx' 或者 store.$patch({属性:xxx})
- 替换state: store.$state = { count: 666 } 或者 pinia.state.value = {}
- 订阅状态:store.$subscribe((mutation, state) => {})
- watch store
watch(
pinia.state,
(state) => {
// 监听每次变化
console.log(state)
},
{ deep: true }
)
getters
computed计算属性,通过store.属性名 获取
action
methods方法,订阅方式:store.$onAction()
注意: store被订阅的时候,当组件被卸载时,store将被自动删除,如果不想被删除,则需要如下方式设置
store.$subscribe(callback, { detached: true }) // 设置detached=ture,则组件卸载时store不被删除