Pinia 状态机
一、下载 pinia
yarn add pinia
二、配置 pinia
1、全局挂载
import { createPinia } from 'pinia'
const app = createApp(App);
app.use(createPinia())
app.mount('#app');
2、创建模块文件
src
|--- store
| |--- global.ts
| |--- users.ts
| |--- ...
3、配置模块
import { defineStore } from 'pinia';
import { getMenusApi } from '../api/user';
export const useGlobal = defineStore('global', {
state: () => ({
menusData: []
}),
getters: {},
actions: {
async getMenusAsync() {
const res = await getMenusApi()
this.menusData = res;
}
}
})
4、组件操作状态机
(1)获取状态机数据
import { useGlobal } from '../../store/global';
const globalStore = useGlobal();
console.log(globalStore.menusData);
(2)调用状态机方法
import { onMounted } from 'vue'
import { useGlobal } from '../../store/global';
const globalStore = useGlobal();
onMounted(() => {
globalStore.getMenusAsync();
})