挂载 Pinia 插件至 Vue 实例上
// main.js 以 Vue 插件的形式挂载 pinia 的实例import { createApp } from 'Vue';import { createPinia } from 'pinia';import App from './App.vue';const pinia = createPinia();createApp(App).use(pinia).mount('#app');
创建 Store
- 定义状态容器和数据
- 修改容器的 state
- 仓库中 action 的使用
defineStore 定义 Store
- id
- options
- state
- getters
- actions
- return function ```javascript import { defineStore } from ‘pinia’;
export const mainStore = defineStore(‘main’, { state: () => ({ helloWorld: ‘Hello World!’, count: 0, phone: ‘15000000888’ }), getters: { phoneHidden(state) { // 可以使用 this // return this.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/, ‘$1**$2’);
return state.phone.toString().repleace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');}
}, actions: { changeState() { this.count ++; this.helloWorld = ‘ByeBye’; } }, });
<a name="gUCHi"></a># 在 Vue 中引用 Store```vue<template><div>{{ store.helloWorld }}</div></template><script setup>import { mainStore } from '../store/index';const store = mainStore();</script>
改变状态数据
直接修改 store 对应的 state
<template><div>{{ store.count }}</div><button @click="handleClick">修改状态数据</button><hr /><div>{{ count }}</div><div>{{ helloWorld }}</div></template><script setup>import { storeToRefs } from 'pinia';import { mainStore } from '../store/index';const store = mainStore();const handleClick = () => {store.count ++;}// 和 Vue Reactive 一样,使用 ES6 解构方式会失去响应性,要使用 Pinia 提供的 storeToRefsconst { helloWorld, count } = storeToRefs(store);</script>
$patch 方法
- 支持并优化适合多个 state 的修改
参数可以为对象或函数
<template><div>{{ store.count }}</div><button @click="handleClick1">修改状态数据 $patch 对象</button><button @click="handleClick2">修改状态数据 $patch 函数</button></template><script setup>import { storeToRefs } from 'pinia';import { mainStore } from '../store/index';const store = mainStore();const handleClick1 = () => {store.$patch({count: store.count ++,helloWorld: store.helloWorld === 'ByeBye' ? 'Hello World!' : 'ByeBye'});}// 这种方式更像使用 immer 的 react-sagaconst handleClick2 = () => {store.$patch((state) => {state.count ++;state.helloWorld = state.helloWorld === 'ByeBye' ? 'Hello World!' : 'ByeBye';})}</script>
使用 action
<template><div>{{ phoneHidden }}</div></template><script setup>import { storeToRefs } from 'pinia';import { mainStore } from '../store/index';const store = mainStore();const { phoneHidden } = storeToRefs(store);</script>
Getters 使用
和 Vuex 一样,Getters 与 Vue 中的 Computed 计算属性作用相似,具有缓存的特性
<template><div>{{ store.phone }}</div></template><script setup>import { mainStore } from '../store/index';const store = mainStore();</script>
Store 相互调用
import { defineStore } from 'pinia';import { otherStore } from './other';export const masterStore = defineStore('master', {state: () => ({phone: '1111111111',}),actions: {getList(){console.log(otherStore().list);}}});
```javascript import { defineStore } from ‘pinia’;
export const otherStore = defineStore(‘other’, { state: () => ({ list: [‘a’, ‘b’, ‘c’] }), }); ```
Vue-devtools 调用

定义 Store 的 ID 会在这里显示作为识别
