1. 安装及挂载
首先使用包管理器进行安装:yarn add pinia
创建实例后并挂载至全局(Vue3)
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');
2. 创建store
创建store需要使用defineStore(),改函数的第一个参数是应用程序中Store的唯一ID
import { defineStore } from 'pinia';
export default useTempStore = defineStore('temp', {
// 其他配置信息:state、getters、actions
});
3. 配置store
- State:用于保存store的全局状态数据
- Getters:用于获取 Store 的状态值的函数,Getter 不会改变 Store 的状态,只是对状态进行了进一步的处理或计算,可以看作是 Store 中的计算属性
- Actions:用于执行一系列操作或逻辑的函数。它用于处理异步操作、提交 Mutations、调用其他 Actions 等,可以被组件或其他 Actions 调用
import { defineStore } from 'pinia';
export default useTempStore = defineStore('temp', {
// State
const count = ref(0);
// Actions
const increment = () => {
count.value++;
};
return { count, increment };
});
4. 使用
- 获取State:需要使用storeToRefs,保证响应式变化
- 获取Action:直接解构store即可
<script setup>
import { storeToRefs } from 'pinia';
import { useTempStore } from '@/stores/counter';
const store = useTempStore();
// 保证响应性,使用storeToRefs获取state
const { count } = storeToRefs(store);
// actions可以直接解构获取
const { increment } = store;
</script>