Vue uses pinia to manage data
Vue3 + TS
step:
existRegister
pinia
import { createPinia } from 'pinia' const pinia = createPinia() (pinia)
Create a filestore/modules/
, used to manage the data of the home module
import { defineStore } from 'pinia' const useHomeStore = defineStore('home',{ state:()=>({ name:'tony' }) }) export default useHomeStore
createstore/
Unified management of all modules
import useHomeStore from './modules/home' const useStore = () => { return { home:useHomeStore() } } export default useStore
test
import useStore from '@/store' const { home } = useStore() ()
Practical operation: Use Pinia to obtain header class navigation
existstore/modules/
state and actions are provided in
const useHomeStore = defineStore('home',{ state:() =>({ categoryList:[] }), actions:{ aysnc getAllCategory(){ const {data} = await ('/home/category/head') = } } })
existLayout/
Send request in
<script setup lang="ts"> import useStore from '@/store' const { home } = useStore() () </script>
TS type declaration file
Define type declaration
existsrc\types\api\
Define data types in
// Classified data single item typeexport 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[]; }; // Classified data list typeexport type CategoryList = Category[];
Unified export type
Newsrc\types\
// Unified export of all types of filesexport * from "./api/home";
application
Revisestore/modules/
,Giveaxios
Request to add generics
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 ("/home/category/head"); = ; }, }, }); export default useHomeStore;
Axios secondary packaging
src\utils\
-import axios from "axios"; +import axios, { type Method } from "axios"; const instance = ({ baseURL: "xxx", timeout: 5000, }); // Add a request interceptor( function (config) { // What to do before sending a request return config; }, function (error) { // What to do about the request error return (error); } ); // Add a response interceptor( function (response) { return response; }, function (error) { // Do something to respond to errors return (error); } ); + // The interface data format returned by the backend+ interface ApiRes<T = unknown> { + msg: string; + result: T; + } +/** + * axios secondary packaging, integrating TS type + * @param url Request address + * @param method Request type + * @param submitData object type, submit data + */ +export const http = <T>(method: Method, url: string, submitData?: object) => { + return <ApiRes<T>>({ + url, + method, + // 🔔 Automatically set the appropriate params/data key name. If the method is get, use params to pass the request parameters, otherwise use data+ [() === "GET" ? "params" : "data"]: submitData, + }); +}; export default instance;
usestore/modules/
import { defineStore } from 'pinia' -import request from "@/utils/request"; +import { http } from "@/utils/request"; const useHomeStore = defineStore('home',{ state:()=>({ name:'tony' }), actions: { async getAllCategory() { - const res = await <ApiRes<CategoryList>>("/home/category/head"); + // It's much simpler to use+ const res = await http<CategoryList>("GET", "/home/category/head"); = ; }, }, }) export default useHomeStore
pinia persistent storage
Target:passPinia
Plugins quickly realize persistent storage.
Plugin documentation:Click to view
usage
Install
yarn add pinia-plugin-persistedstate # ornpm i pinia-plugin-persistedstate
Using plug-ins
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate' const pinia = createPinia(); (piniaPluginPersistedstate); (pinia);
Module enables persistence
const useHomeStore = defineStore("home",()=>{ ... }, // defineStore third parameter { // Add configuration to enable state/ref persistent storage // The plug-in stores all state/ref by default persist: true, } );
Frequently Asked Questions
Can Vue2 use Pinia and persistent storage plug-ins?
- It can be used, and you need to cooperate with @vue/composition-api to let Vue2 old projects support the combined API first.
- Pinia can be used in a combined API.
After the module is persisted, will the data change in the future? What should I do?
- Read the local data first. If a new request obtains new data, the new data will be automatically overwritten with the old data.
- No additional processing is required, the plug-in will update to the latest data by itself.
Advanced usage (persistence required data on demand)
Requirements: If you don’t want all data to be processed persistently, can you persist the required data as needed? What should you do?
The data of certain modules can be cached as needed using configuration writing.
import { defineStore } from 'pinia' export const useStore = defineStore('main', { state: () => { return { someState: 'hello pinia', nested: { data: 'nested pinia', }, } }, // All data persistence // persist: true, // Other configurations of persistent storage plug-in persist: { //Storage state/ref on demand // Modify the key name used in the storage, default to the id of the current Store key: 'storekey', // Modify to sessionStorage, default to localStorage storage: , // 🎉Permanent on demand, and if you don't write by default, it will store all paths: [''], }, })
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.