一、准备环境
1.1、create-vue
npm init vue@latest
1.2、安装pinia
yarn add pinia
得到如下内容
二、使用
js
// src/main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
createApp(App)
.use(createPinia())
.mount('#app')
2.1、state
js
// src/store/index.ts
import { defineStore } from 'pinia'
export const useUserStores = defineStore('userInfo',{
state: () => {
return{
name: "jeck ma",
like: ['apple','orange']
}
}
})
2.1.1不使用setup()
js
// 不使用setup()
// App.vue
<script setup>
import { useUserStores } from '@/store';
const userStore = useUserStores();
</script>
<template>
<div>
{{ userStore.name }}
</div>
</template>
2.1.2使用setup()
js
// App.vue
<script>
import { useUserStores } from '@/store'
export default {
setup() {
const userStore = useUserStores();
return {
userStore
}
},
}
</script>
<template>
<div>
{{ userStore.name }}喜欢的水果是:{{ userStore?.like?.join("、") || '暂无'}}
</div>
</template>
2.2在devtools中
2.3重置状态
您可以通过调用 store 上的 $reset() 方法将状态 重置 到其初始值:
js
const userStore = useUserStores()
userStore.$reset()
2.4改变状态
除了直接用 userStore.name+="age=30" 修改 store,你还可以调用 $patch 方法。 它允许您使用部分“state”对象同时应用多个更改:
js
userStore.$patch({
like: ['apple','orange','banana']
})
但是,使用这种语法应用某些突变非常困难或代价高昂:任何集合修改(例如,从数组中推送、删除、拼接元素)都需要您创建一个新集合。 正因为如此,$patch 方法也接受一个函数来批量修改集合内部分对象的情况:
js
userStore.$patch((state) =>{
state.like.push("banana")
})
2.5替换state
您可以通过将其 $state 属性设置为新对象来替换 Store 的整个状态:
js
store.$state = userStore.$state = {
name: 'jeckli',
like: ['橘子','人生果']
}
2.6订阅状态
可以通过 store 的 $subscribe() 方法查看状态及其变化,类似于 Vuex 的 subscribe 方法。 与常规的 watch() 相比,使用 $subscribe() 的优点是 subscriptions 只会在 patches 之后触发一次(例如,当使用上面的函数版本时)。
js
cartStore.$subscribe((mutation, state) => {
// import { MutationType } from 'pinia'
mutation.type // 'direct' | 'patch object' | 'patch function'
// 与 cartStore.$id 相同
mutation.storeId // 'userInfo'
// 仅适用于 mutation.type === 'patch object'
mutation.payload // 补丁对象传递给 to userInfo.$patch()
})
默认情况下,state subscriptions 绑定到添加它们的组件(如果 store 位于组件的 setup() 中)。 意思是,当组件被卸载时,它们将被自动删除。 如果要在卸载组件后保留它们,请将 { detached: true } 作为第二个参数传递给 detach 当前组件的 state subscription:
js
// 此订阅将在组件卸载后保留
userStore.$subscribe(callback, { detached: true })
三、对比vuex
相对来说,vuex在对state的操作上,多了更多好用的API。比如重置($reset())、修改($patch)、替换。