Pinia

Pinia

  • Pinia 是一个用于 Vue 的状态管理库,类似 Vuex, 是 Vue 的另一种状态管理方案,Pinia 支持 Vue2 和 Vue3
  • 优势:易于学习,极轻1KB,模块化设计便于拆分状态

引入

    // src/stores/index.ts
    import Vue from 'vue';
    import { createPinia, PiniaVuePlugin } from 'pinia';
    Vue.use(PiniaVuePlugin);
    export const pinia = createPinia();
    // src/main.ts
    import { pinia } from './stores';
    import router from './router';
    async function main() {
        await prepareApp();
        createApp({
            pinia,
            router,
            render: () => h(App),
        }).mount('#app');
    }
    main().catch(console.error);

使用

    // src/stores/user.ts 如需存储用户信息
    import { defineStore } from 'pinia';
    import { readonly, ref } from 'vue-demi';
    export type UserInfo = {
        id: string;
        account: string;
        name: string;
    };
    const USER_STORE = 'USER_STORE';
    export const useUserStore = defineStore(USER_STORE, () => {
        const info = ref<UserInfo | null>(null);
        const setUserInfo = (data: UserInfo | null) => {
            info.value = data;
        };
        return {
            info: readonly(info),
            setUserInfo,
        };
    });
  • 存储
// src/utils/useInterceptors.ts axios拦截器文件
import type VueRouter from 'vue-router';
export function useInterceptors(axios: AxiosInstance, router: VueRouter) {
// 省略axios拦截器逻辑
router.beforeEach(async (to, from, next) => {
		const $userStore = useUserStore();
		// 登录或者meta中auth为false则直接进入页面
		if (to.name === 'login'||to.meta?.auth===false) {
			next();
		} else {
			try {
				let userDetail = await getUser();// 获取用户接口方法
				$userStore.setUserInfo(userDetail);
				next();
			} catch (e) {
				next(false);
				router.push({ name: 'login' });
			}
		}
	});
}
  • 读取
    <!-- 读取 src/views/TestUser.vue -->
    <script lang="ts" setup>
    import { useUserStore } from '@/stores/user';
    const $userStore = useUserStore();
    onMounted(()=>{
        console.log($userStore.info)
    })
    </script>
    <script lang="ts">
    import { computed, ref, onMounted } from 'vue-demi';
    </script>
上一篇:D③商品列表-添加商品:


下一篇:vue-05