学无先后,达者为师

网站首页 编程语言 正文

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

作者:大橘为重¨ 更新时间: 2023-07-14 编程语言

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

  • 前言
  • 一、安装pinia
  • 二、创建一个store
  • 三、Store 间的相互访问
  • 四、pinia 中常用的内置方法
  • 五、pinia的分模块使用例子
  • 六、补充:composition API 写法


前言

对比于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')

二、创建一个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
		}
    }
})
注:this 可以访问到自身的 store 实例
  • Pinia 创建的 Store 动作被派发为普通的函数调用,不再需要使用dispatch 方法或MapAction 辅助函数
<template>
    <div>
        <p>sum:{{useMainStore.sum}}</p>
        <p>doubleSum:{{useMainStore.getDoubleSum}}</p>
        <button @click="useMainStore.addSum(1)">sum+1</button>
    </div>
</template>

<script setup lang="ts">
import { mainStore } from "../store/index";
const useMainStore = mainStore()

</script>

三、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
        }
    }
})

四、pinia 中常用的内置方法

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

五、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
  • main.ts 文件:
import { createApp } from 'vue'
import App from './App.vue'
import pinia from "./pinia";

createApp(App).use(pinia).mount('#app')
  • 模块文件,这里展示 user 模块:
  • types.ts 文件:
export type RoleType = '' | 'admin' | 'user'

export interface UserState {
    name?: string;
    email?: string;
    phone?: string;
    introduction?: string;
    role: RoleType;
}
  • 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

六、补充: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 }
})

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

原文链接:https://blog.csdn.net/weixin_53068161/article/details/126785114

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新