Vue使用pinia管理数据pinia持久化存储问题

Vue使用pinia管理数据

Vue3 + TS

步骤:

main.ts中注册 pinia

import { createPinia } from 'pinia'

const pinia = createPinia()

app.use(pinia)

创建文件store/modules/home.ts,用于管理home模块的数据

import { defineStore } from 'pinia'

const useHomeStore = defineStore('home',{
    state:()=>({
        name:'tony'
    })
})

export default useHomeStore

创建store/index.ts统一管理所有的模块

import useHomeStore from './modules/home'

const useStore = () => {
    return {
        home:useHomeStore()
    }
}

export default useStore

测试

import useStore from '@/store'
const { home } = useStore()
console.log(home.tony)

实际操作:使用 Pinia 获取头部分类导航

store/modules/home.ts中提供 state 和 actions

const useHomeStore = defineStore('home',{
    state:() =>({
        categoryList:[]
    }),
    actions:{
     aysnc getAllCategory(){
      const {data} = await rquest.get('/home/category/head')
      this.categoryList = data.result                        
     }
    }
})

Layout/index.vue中发送请求

<script setup >
import useStore from '@/store'
const { home } = useStore()
home.getAllCategory()
</script>

TS 类型声明文件

定义类型声明

src\types\api\home.d.ts中定义数据类型

// 分类数据单项类型
export interface Goods {
  desc: string;
  id: string;
  name: string;
  picture: string;
  price: string;
  title: string;
  alt: string;
};

export interface Children {
  id: string;
  name: string;
  picture: string;
  goods: Goods[];
};

export interface Category {
  id: string;
  name: string;
  picture: string;
  children: Children[];
  goods: Goods[];
};

// 分类数据列表类型
export type CategoryList = Category[];

类型出口统一

新建 src\types\index.d.ts

// 统一导出所有类型文件
export * from "./api/home";

应用

修改store/modules/home.ts,给 axios 请求增加泛型

import { defineStore } from "pinia";
import request from "@/utils/request";
import type { CategoryList } from "@/types";

const useHomeStore = defineStore("home", {
  state: () => ({
    categoryList: [] as CategoryList,
  }),
  actions: {
    async getAllCategory() {
      const {data} = await request.get("/home/category/head");
      this.categoryList = data.result;
    },
  },
});

export default useHomeStore;

Axios 二次封装

src\utils\request.ts

-import axios from "axios";
+import axios, { type Method } from "axios";

const instance = axios.create({
  baseURL: "xxx",
  timeout: 5000,
});

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response;
  },
  function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

+ // 后端返回的接口数据格式
+ interface ApiRes<T = unknown> {
+    msg: string;
+    result: T;
+ }

+/**
+ * axios 二次封装,整合 TS 类型
+ * @param url  请求地址
+ * @param method  请求类型
+ * @param submitData  对象类型,提交数据
+ */
+export const http = <T>(method: Method, url: string, submitData?: object) => {
+  return instance.request<ApiRes<T>>({
+    url,
+    method,
+    //