vue3使用pinia封装存储数据
一.安装依赖
npm i pinia
二.封装方法
/stores/selectOptionType.ts
import { defineStore } from "pinia";
import { ElMessage } from "element-plus";
import apis from "/@/api";export const useSelectOptionType = defineStore("selectOptionType", {state: (): any => ({contractpayTypeList: [], // 支付方式}),actions: {// 确认保存数据ConfirmSaveData(Result: any,TypeListName: string,ValueIsNum = false,Label = "name",Value = "id") {if (Result.code === 200) {let newArr = Result.data.map((item: any) => {return {label: item[Label],value: ValueIsNum ? Number(item[Value]) : item[Value],};});this[TypeListName] = newArr;} else {ElMessage({message: Result.message,type: "error",});}},// 支付方式async setContractpayTypeList() {const res: any = await apis.baseinfoSetlist({ settype: "contractpay" });this.ConfirmSaveData(res, "contractpayTypeList");},},
});
/stores/index.ts
// https://pinia.vuejs.org/
import { createPinia } from 'pinia';// 创建
const pinia = createPinia();// 导出
export default pinia;
三.main使用
main.ts
import pinia from "/@/stores/index";
app.use(pinia)
四.vue页面引入和调用
import { storeToRefs } from 'pinia';
import { useSelectOptionType } from '/@/stores/selectOptionType';useSelectOptionType().setContractpayTypeList()
const { contractpayTypeList } = storeToRefs(useSelectOptionType());