Vue怎么使用pinia管理数据

其他教程   发布日期:2023年11月04日   浏览次数:413

这篇文章主要讲解了“Vue怎么使用pinia管理数据”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Vue怎么使用pinia管理数据”吧!

    Vue使用pinia管理数据

    Vue3 + TS

    步骤:

    1. main.ts
    中注册
    1. pinia
    1. import { createPinia } from 'pinia'
    2. const pinia = createPinia()
    3. app.use(pinia)

    创建文件

    1. store/modules/home.ts
    ,用于管理home模块的数据
    1. import { defineStore } from 'pinia'
    2. const useHomeStore = defineStore('home',{
    3. state:()=>({
    4. name:'tony'
    5. })
    6. })
    7. export default useHomeStore

    创建

    1. store/index.ts
    统一管理所有的模块
    1. import useHomeStore from './modules/home'
    2. const useStore = () => {
    3. return {
    4. home:useHomeStore()
    5. }
    6. }
    7. export default useStore

    测试

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

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

    1. store/modules/home.ts
    中提供 state 和 actions
    1. const useHomeStore = defineStore('home',{
    2. state:() =>({
    3. categoryList:[]
    4. }),
    5. actions:{
    6. aysnc getAllCategory(){
    7. const {data} = await rquest.get('/home/category/head')
    8. this.categoryList = data.result
    9. }
    10. }
    11. })

    1. Layout/index.vue
    中发送请求
    1. <script setup lang="ts">
    2. import useStore from '@/store'
    3. const { home } = useStore()
    4. home.getAllCategory()
    5. </script>

    TS 类型声明文件

    定义类型声明

    1. src ypesapihome.d.ts
    中定义数据类型
    1. // 分类数据单项类型
    2. export interface Goods {
    3. desc: string;
    4. id: string;
    5. name: string;
    6. picture: string;
    7. price: string;
    8. title: string;
    9. alt: string;
    10. };
    11. export interface Children {
    12. id: string;
    13. name: string;
    14. picture: string;
    15. goods: Goods[];
    16. };
    17. export interface Category {
    18. id: string;
    19. name: string;
    20. picture: string;
    21. children: Children[];
    22. goods: Goods[];
    23. };
    24. // 分类数据列表类型
    25. export type CategoryList = Category[];

    类型出口统一

    新建

    1. src ypesindex.d.ts
    1. // 统一导出所有类型文件
    2. export * from "./api/home";

    应用

    修改

    1. store/modules/home.ts
    ,给
    1. axios
    请求增加泛型
    1. import { defineStore } from "pinia";
    2. import request from "@/utils/request";
    3. import type { CategoryList } from "@/types";
    4. const useHomeStore = defineStore("home", {
    5. state: () => ({
    6. categoryList: [] as CategoryList,
    7. }),
    8. actions: {
    9. async getAllCategory() {
    10. const {data} = await request.get("/home/category/head");
    11. this.categoryList = data.result;
    12. },
    13. },
    14. });
    15. export default useHomeStore;

    Axios 二次封装

    1. srcutils
    2. equest.ts
    1. -import axios from "axios";
    2. +import axios, { type Method } from "axios";
    3. const instance = axios.create({
    4. baseURL: "xxx",
    5. timeout: 5000,
    6. });
    7. // 添加请求拦截器
    8. instance.interceptors.request.use(
    9. function (config) {
    10. // 在发送请求之前做些什么
    11. return config;
    12. },
    13. function (error) {
    14. // 对请求错误做些什么
    15. return Promise.reject(error);
    16. }
    17. );
    18. // 添加响应拦截器
    19. instance.interceptors.response.use(
    20. function (response) {
    21. return response;
    22. },
    23. function (error) {
    24. // 对响应错误做点什么
    25. return Promise.reject(error);
    26. }
    27. );
    28. + // 后端返回的接口数据格式
    29. + interface ApiRes<T = unknown> {
    30. + msg: string;
    31. + result: T;
    32. + }
    33. +/**
    34. + * axios 二次封装,整合 TS 类型
    35. + * @param url 请求地址
    36. + * @param method 请求类型
    37. + * @param submitData 对象类型,提交数据
    38. + */
    39. +export const http = <T>(method: Method, url: string, submitData?: object) => {
    40. + return instance.request<ApiRes<T>>({
    41. + url,
    42. + method,
    43. + // ???? 自动设置合适的 params/data 键名称,如果 method 为 get 用 params 传请求参数,否则用 data
    44. + [method.toUpperCase() === "GET" ? "params" : "data"]: submitData,
    45. + });
    46. +};
    47. export default instance;

    使用

    1. store/modules/home.ts
    1. import { defineStore } from 'pinia'
    2. -import request from "@/utils/request";
    3. +import { http } from "@/utils/request";
    4. const useHomeStore = defineStore('home',{
    5. state:()=>({
    6. name:'tony'
    7. }),
    8. actions: {
    9. async getAllCategory() {
    10. - const res = await request.get<ApiRes<CategoryList>>("/home/category/head");
    11. + // 使用起来简洁很多
    12. + const res = await http<CategoryList>("GET", "/home/category/head");
    13. this.categoryList = res.data.result;
    14. },
    15. },
    16. })
    17. export default useHomeStore

    pinia 持久化存储

    目标: 通过

    1. Pinia
    插件快速实现持久化存储。

    插件文档:点击查看

    用法

    安装

    1. yarn add pinia-plugin-persistedstate
    2. # 或
    3. npm i pinia-plugin-persistedstate

    使用插件

    1. import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
    2. const pinia = createPinia();
    3. pinia.use(piniaPluginPersistedstate);
    4. app.use(pinia);

    模块开启持久化

    1. const useHomeStore = defineStore("home",()=>{
    2. ...
    3. },
    4. // defineStore 第三个参数
    5. {
    6. // 添加配置开启 state/ref 持久化存储
    7. // 插件默认存储全部 state/ref
    8. persist: true,
    9. }
    10. );

    常见疑问

    Vue2 能不能用 Pinia 和 持久化存储插件。

    • 可以使用,需配合 @vue/composition-api 先让 Vue2 老项目支持 组合式API。

    • Pinia 能在 组合式API 中使用。

    模块做了持久化后,以后数据会不会变,怎么办?

    • 先读取本地的数据,如果新的请求获取到新数据,会自动把新数据覆盖掉旧的数据。

    • 无需额外处理,插件会自己更新到最新数据。

    进阶用法(按需持久化所需数据)

    需求:不想所有数据都持久化处理,能不能按需持久化所需数据,怎么办?

    可以用配置式写法,按需缓存某些模块的数据。

    1. import { defineStore } from 'pinia'
    2. export const useStore = defineStore('main', {
    3. state: () => {
    4. return {
    5. someState: 'hello pinia',
    6. nested: {
    7. data: 'nested pinia',
    8. },
    9. }
    10. },
    11. // 所有数据持久化
    12. // persist: true,
    13. // 持久化存储插件其他配置
    14. persist: {
    15. // 按需存储 state/ref
    16. // 修改存储中使用的键名称,默认为当前 Store的 id
    17. key: 'storekey',
    18. // 修改为 sessionStorage,默认为 localStorage
    19. storage: window.sessionStorage,
    20. // ????按需持久化,默认不写会存储全部
    21. paths: ['nested.data'],
    22. },
    23. })

    以上就是Vue怎么使用pinia管理数据的详细内容,更多关于Vue怎么使用pinia管理数据的资料请关注九品源码其它相关文章!