一、创建 Pinia 并暴露
import { createPinia } from 'pinia'; // 引入 pinia
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'; // 持久化存储
const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);
export default pinia;
二、vue3 中的 main.js 引入 Pinia
import { createApp } from 'vue';
const app = createApp(App);
app.use(pinia);
app.mount('#app');
三、创建 Pinia的 模块仓库
import { defineStore } from 'pinia';
export const userStore = defineStore('login', {
persist: true, // 开启数据持久化
state: () => ({ count: 0 }),
getters: {
getCount: (state) => state.count,
},
actions: {
add(){
this.count++
}
},
});
四、在组件中使用 Pinia的数据
1、同步
<script setup>
import { userStore } from './store/user'; // 引入模块
const store = userStore();
console.log('store.count------->', store.count); // 获取模块中的数据
store.count++; // 直接修改数据
console.log('store.count------->', store.count);
</script>
2、异步
// vue组件
<script setup>
import { userStore } from '@/store/user';
const { ref } = require('@vue/reactivity');
const mobile = ref('13800000002');
const password = ref('123456');
const store = userStore();// 使用pinia状态集中管理仓库
const handlerLogin = async () => {
await store.userLogin({ mobile: mobile.value, password: password.value });
};
</script>
/*-------------------------------------------------------------------------------*/
// pinia模块
import user from '@/api/user';
import { defineStore } from 'pinia';
export const userStore = defineStore('login', {
persist: true, // 开启数据持久化
state: () => ({ token: '', count: 0 }),
getters: {
getToken: (state) => state.token,
},
actions: {
async userLogin(userInfo) {
const { data } = await user.login(userInfo);
this.token = data && data.data;
},
},
});