安装 pinia
yarn add pinia
# or with npm
npm install pinia
引入 pinia
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
app.mount('#app')
定义 store
import { defineStore } from 'pinia'
// useStore could be anything like useUser, useCart
// the first argument is a unique id of the store across your application
export const useStore = defineStore('main', {
// other options...
state: () => ({}),
getters: {},
actions: {}
})
组件中使用 store
<script setup lang="ts">
import { useStore } from '@/stores/counter'
const store = useStore()
// store.xxx
</script>
store 特性
-
store 本身是 proxy 对象,在标签中直接使用具有响应式
-
解构出来的元素没有响应式,可以通过
storeToRefs包裹 store,这样结构出来的数据也具有响应式<script setup lang="ts"> import { storeToRefs } from 'pinia' import useMainStore from '@/store/main' const store = useMainStore() const { num, arr } = storeToRefs(store) </script>
store 相关
修改 state 中的值
// 1、修改一个值
store.xxx = xxx
// 2、可以修改多个值
store.$patch({
xxx1: xxx,
xxx2: xxx
})
store.$patch((state) => {
// state 就是 store 中的 state
// 逻辑
state.xxx = xxx
})
// 3、通过 actions 中的函数进行修改,changeState 在 store 中的 actions 中定义
store.changeState()
// 4、修改整个 state
store.$state = {}
getters
- 类似于 computed,有缓存机制
- getters 之间可以相互调用
actions
- actions 中的方法可以是同步和异步两种写法
- actions 中的方法可以相互调用
store 中的其他方法
$reset
store.$reset(),重置 store 最开始的数据
$subscribe
当 state 中的任何数据发生改变时,都会触发$subscribe函数传入的函数 官网
参数args是 store 配置的一些信息
参数state是 store 中改变后的数据
store.$subscribe((args, state) => {
// store 中的数据发生改变后,执行的逻辑
}, {})
$onAction
当调用 store 中的函数时,会被监听到 官网
参数args
after是监听到变化,且传入的函数执行完后,执行afterargs是执行函数传入的参数onError捕获函数调用执行时的错误
store.$onAction((args) => {
// store 中的函数被调用后,执行的逻辑
})
$patch
修改 store 中的值
// 可以修改多个值
// 写法 1
store.$patch({
xxx1: xxx,
xxx2: xxx
})
// 写法 2
store.$patch((state) => {
// state 就是 store 中的 state
// 逻辑
state.xxx = xxx
})