• pinia的常用知识点及搭配“script setup”的使用



    前言

    对比于vuex,新的Vue状态管理库pinia更加的轻量。并且具有更加明显的优势,包括有:抛弃传统的 mutation,通过action对同异步进行操作简化状态管理库;不需要嵌套模块,让代码扁平化;更好的TypeScript支持;更友好的调用方式等。同时结合vue3.2推出的setup语法糖使用会得到更加友好的体验。

    一、安装pinia

    1. npm 安装

    npm install pinia

    1. main.ts下导入pinia
    import { createApp } from 'vue'
    import App from './App.vue'
    import { createPinia } from 'pinia'
    
    createApp(App).use(createPinia()).mount('#app')
    
    • 1
    • 2
    • 3
    • 4
    • 5

    二、创建一个store

    项目结构:
    在这里插入图片描述

    • 导入 “defineStore()”
    • 为每个 store 规定唯一的命名
    • 按需创建 state、getters、actions 部分操作
    import { defineStore } from 'pinia'
    
    export const mainStore = defineStore('main', {
        state: () => ({
        	// 在该项中可以自定义状态数据
            // ......
            sum:0
        }),
        getters: {
        	// 该项等同于 Store 状态的 计算值,类似于计算属性
            // ......
            getDoubleSum(state) {
            	return state.sum*2
            }
        }
        actions: {
        	// 相当于组件中的 methods,用于定义和处理业务逻辑
            //.......
            addSum(value: number) {
            	this.sum += value
    		}
        }
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    注:this 可以访问到自身的 store 实例
    • Pinia 创建的 Store 动作被派发为普通的函数调用,不再需要使用dispatch 方法或MapAction 辅助函数
    <template>
        <div>
            <p>sum:{{useMainStore.sum}}p>
            <p>doubleSum:{{useMainStore.getDoubleSum}}p>
            <button @click="useMainStore.addSum(1)">sum+1button>
        div>
    template>
    
    <script setup lang="ts">
    import { mainStore } from "../store/index";
    const useMainStore = mainStore()
    
    script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    三、Store 间的相互访问

    • 调用对应创建的 “Store方法” 即可获取实例使用

    例如:

    import { defineStore } from 'pinia'
    
    export const mainStore = defineStore('main', {
        state: () => ({
            sum: 0,
        }),
    })
    
    export const otherStore = defineStore('other', {
        state: () => ({
            doubleSum: 0
        }),
        getters: {
            updateDoubleSum(state) {
            	// 获取 "mainStore" 的实例,并使用其中的 sum 状态
                const useMainStore = mainStore()
                state.doubleSum = useMainStore.sum * 2
                return state.doubleSum
            }
        }
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    四、pinia 中常用的内置方法

    • 重置状态到初始值
    • 通过调用 store 上的 $reset() 方法可将状态重置
    const store = useStore()
    store.$reset()
    
    • 1
    • 2
    • 一次更改多个状态
    • 通过调用 store 上的 $patch 方法,支持使用部分 “state” 对象同时应用多个更改
    const store = useStore()
    store.$patch({
      counter: store.counter + 1,
      name: 'Abalam',
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5

    五、pinia的分模块使用例子

    项目结构:
    在这里插入图片描述

    • index.ts 文件:
    import { createPinia } from 'pinia'
    import useUserStore from "./modules/user/index";
    import useAppStore from "./modules/app/index";
    
    const pinia = createPinia()
    
    export { useUserStore, useAppStore }
    export default pinia
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • main.ts 文件:
    import { createApp } from 'vue'
    import App from './App.vue'
    import pinia from "./pinia";
    
    createApp(App).use(pinia).mount('#app')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 模块文件,这里展示 user 模块:
    • types.ts 文件:
    export type RoleType = '' | 'admin' | 'user'
    
    export interface UserState {
        name?: string;
        email?: string;
        phone?: string;
        introduction?: string;
        role: RoleType;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • index.ts 文件:
    import { defineStore } from "pinia";
    import type { UserState, RoleType } from "./types";
    import { getUserInfo } from "@/network/test";
    
    const useUserStore = defineStore('user',{
        state:():UserState=>({
            name: undefined,
            email: undefined,
            phone: undefined,
            introduction: undefined,
            role:''
        }),
        getters:{
            userInfo(state:UserState):UserState {
                return {...state}
            }
        },
        actions:{
            setRole(role: RoleType) {
                this.role = role
            },
            setInfo(partial: Partial<UserState>) {
                this.$patch(partial);
            },
            resetInfo() {
                this.$reset()
            },
            async info() {
                const res:any = await getUserInfo();
                this.setInfo(res.data);
            },
        }
    })
    
    export default useUserStore
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    六、补充:composition API 写法

    上面的store均使用 options API 的写法,以下我们改为使用 composition API 模式定义store,改写法更符合Vue3 setup的编程模式,让结构更加扁平化,写法转化如下:

    • 使用 ref、reactive 定义的变量代替 options API中的state;
    • 使用 computed 代替 options API中的getters;
    • 直接书写 函数代替 options API中的actions;

    现在我们使用上面的写法把“目录一”创建的store改为 composition API 的写法:

    import { defineStore } from 'pinia'
    import { ref, computed } from 'vue'
    
    export const mainStore = defineStore('main', ()=>{
    	const sum = ref<number>(0)
    	const doubleSum = computed<number>(() => sum.value * 2)
    	const addSum = (value: number) => {
    		sum.value += value
    	}
    	
    	return { sum, doubleSum, addSum }
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    提示:文章到此结束,文章仅为个人学习记录,若有不足还请大家指出。

  • 相关阅读:
    Docker 常用命令
    C/C++的内存管理
    canvas的常用函数
    基于Java的智能停车场管理系统设计与实现(源码+lw+部署文档+讲解等)
    数字图像处理大作业
    华为OD机试 - 羊、狼、农夫过河 - 逻辑分析(Java 2022 Q4 100分)
    MySQL(4)索引实践(2)
    Docker学习笔记(一)安装Docker、镜像操作、容器操作、数据卷操作
    软考高级之系统架构师之计算机基础
    【算法集训 | 暑期刷题营】终章
  • 原文地址:https://blog.csdn.net/weixin_53068161/article/details/126785114