其他分享
首页 > 其他分享> > Pinia

Pinia

作者:互联网

Pinia

引入

    // 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>

标签:info,const,Pinia,stores,pinia,router,import
来源: https://blog.csdn.net/qq_39331257/article/details/122579447