pinia
-
安装:
yarn add pinia # or with npm npm install pinia
vue3引入(vue2引入需要使用插件)
import { createPinia } from 'pinia'
app.use(createPinia())
vue2引入
import { createPinia, PiniaVuePlugin } from 'pinia'
Vue.use(PiniaVuePlugin)
const pinia = createPinia()
new Vue({
el: '#app',
// other options...
// ...
// note the same `pinia` instance can be used across multiple Vue apps on
// the same page
pinia,
})
pinia可以每一个模块儿创建一个商店(包含state、getters、action)
如:store/modules/common
import { defineStore } from 'pinia'
export const useCommon = defineStore('common'/id/, {
state: () => {
return {
counter: 0,
name: 'Eduardo',
isAdmin: true,
}
},
})
在页面中改变值:
// 改变单个值 store.counter ++; // 改变多个值 store.$patch({ counter: store.counter ++, name: 'ha' }); // 改变多个值 可以接受函数 store.$patch((state) => { state.array.push(1); state.name = 'en'; });
重置状态:
store.$reset()
更换state
$state您可以通过将商店的属性设置为新对象来替换商店的整个状态:
store.$state = { counter: 666, name: 'Paimon' }
还可以通过更改实例state的来替换应用程序的整个状态
pinia.state.value = {}
订阅状态$subscribe
cartStore.$subscribe((mutation, state) => { // import { MutationType } from 'pinia' mutation.type // 'direct' | 'patch object' | 'patch function' // same as cartStore.$id mutation.storeId // 'cart' // only available with mutation.type === 'patch object' mutation.payload // patch object passed to cartStore.$patch() // persist the whole state to the local storage whenever it changes localStorage.setItem('cart', JSON.stringify(state)) })
默认情况下,状态订阅绑定到添加它们的组件(如果存储在组件的内部setup())。意思是,当组件被卸载时,它们将被自动删除。如果要在组件卸载后保留它们,请{ detached: true }作为第二个参数传递以从当前组件中分离状态订阅:
export default { setup() { const someStore = useSomeStore() // this subscription will be kept after the component is unmounted someStore.$subscribe(callback, { detached: true }) // ... }, }
查看实例上的整个状态:
watch( pinia.state, (state) => { // persist the whole state to the local storage whenever it changes localStorage.setItem('piniaState', JSON.stringify(state)) }, { deep: true } )
getter: 相当于计算属性
import { defineStore } from 'pinia'
const array: any[] = []
export const useCommon = defineStore('common', {
state: () => {
return {
counter: 0,
name: 'Eduardo',
isAdmin: true,
array: array
}
},
getters: {
doubleCount(state):number{
return state.counter * 2
},
doubleCountPlusOne():number {
// autocompletion ✨
return this.doubleCount + 1;
},
}
})
使用和state一样
console.log(store.doubleCountPlusOne)
将参数传递给 getter
getters: { getUserName():any { return (userName:string) => [{name: 'zhangsan'}, {name: 'lisi'}].find(item => item.name === userName); } }
调用
store.getUserName('zhangsan') // { "name": "zhangsan" }
actions:
actions: { increment() { this.counter++ }, randomizeCounter() { this.counter = Math.round(100 * Math.random()) }, }
也可以返回promise,总之可以随意根据自己的意愿返回任意结果
调用
store.increment();
store.randomizeCounter()
相对于vuex,调用方便了很多
$onAction监听商店的所有action
const unsubscribe = store.$onAction( // name: action的函数名称 store商店实例 args:传给action的参数 after:action执行完后的钩子函数,参数为返回值 onError:action报错后的钩子函数 ({ name, store, args, after, onError }) => { console.log(name, 'name'); console.log(store, 'store'); console.log(args, 'args'); after(result => { console.log(result, 'result'); }) onError(err => { console.log(err, 'err'); }) } ); // unsubscribe(); // 取消监听
默认会随组件销毁而销毁,如果不想随组件销毁,可以穿第二个参数为true
const someStore = useSomeStore() // this subscription will be kept after the component is unmounted someStore.$onAction(callback, true)
插件 略
-

浙公网安备 33010602011771号