安装pinia
pnpm add pinia
Pinia 官网 传送门
main.js引入
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } 'pinia'
const app = createApp(App);
app.use(createPinia())
app.mount("#app")
创建一个pinia,scr/stores/index
import { defineStore } from 'pinia'
import { res } from 'vue'
export default defineStore('store',{
const name = ref('名称')
const items = ref([])
return { name, items }
})
vue组件使用
import useStore from "@/stores/index"
import { storeToRefs } from 'pinia'
const store = useStore()
console.log(useStore.name)
// 解决解构后丢失响应式,引用 storeToRefs
const { name } = storeToRefs(store);
// 取值
store.name
// 单个修改
store.name = "Abalam"
// 修改普通数据类型
store.$patch({
// counter: store.counter + 1,
name: 'Abalam',
})
// 修改普通数据类型 + 复杂数据类型
cartStore.$patch((state) => {
state.items.push({ name: 'shoes', quantity: 1 })
state.name = 'Abalam'
})
// 替换state,源码底层也是通过store.$patch去修改的
store.$state = { name:'Abalam', }
pinia 组合式API reset实现 main.js
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } 'pinia'
const app = createApp(App);
const pinia = createPinia();
pinia.use(store => {
const beforeStore = store.$state; // 需要深度拷贝
store.$reset = () => {
store.$state = beforeStore // 需要深度拷贝
}
})
app.use(pinia)
app.mount("#app")
订阅pinia的监听
import useStore from "@/stores/index"
const store = useStore()
store.$subscribe((mutation, state) => {
// import { MutationType } from 'pinia'
mutation.type // 'direct' | 'patch object' | 'patch function'
// 与 cartStore.$id 相同
mutation.storeId // 'cart'
// 仅适用于 mutation.type === 'patch object'
mutation.payload // 补丁对象传递给 to cartStore.$patch()
// 每当它发生变化时,将整个状态持久化到本地存储
localStorage.setItem('store', JSON.stringify(state))
})
// 此订阅将在组件卸载后保留
store.$subscribe(callback, { detached: true })