Vue3.0(七):Pinia状态管理

Pinia状态管理

最初是作为一个实验为 Vue重新设计状态管理,让它用起来像组合式API

Pinia和Vuex的对比

  • 为什么要用 Pinia
    • Pinia 最初是为了 探索Vuex的下一次迭代 会是什么样子,结合了 Vuex5核心团队讨论中的很多想法
    • 最终,团队意识到 Pinia已经实现了Vuex5中大部分的内容 ,所以最终决定 使用Pinia来代替Vuex
    • 与Vuex相比,Pinia提供了一个更加简单的API,具有更少的仪式 ,提供了 Composition-API风格的API
    • 最重要的是,能够更好的支持TypeScript
  • 与Vuex相比,Pinia的优势
    • 比如mutations不再存在
    • 更友好的支持TypeScript
    • 不再有modules
    • 不再有命名空间的概念,不需要记住复杂的关系

如何使用Pinia

  • 首先通过 npm install pinia安装pinia
  • 安装完成后,在src文件夹下面创建store文件夹
  • 创建index.js的入口文件
js 复制代码
import { createPinia } from "pinia";

export default createPinia();
  • 在main.js使用pinia插件
js 复制代码
import { createApp } from "vue";
import App from "./App.vue";
import pinia from "./store";

const app = createApp(App);
app.use(pinia);

app.mount("#app");
  • 在store文件夹下面创建不同的store
    • 创建一个counter.js的store文件,用于保存计数的状态
js 复制代码
import { defineStore } from "pinia";

//defineStore创建store,可以创建多个store
//第一个参数是用于命名store的
//第二个参数是store的具体内容
const useCounter = defineStore("counter", {
  state: () => ({
    count: 199,
  }),
});

//返回值是一个函数,将函数暴露出去
export default useCounter;
  • 而后在具体的组件中引入暴露的函数,完成调用即可
html 复制代码
<template>
  <!-- 直接访问store中的变量即可 -->
  {{ counterStore.count }}
</template>

<script setup>
//引入暴露的store函数
import useCounter from "./store/counter.js";
const counterStore = useCounter();
</script>

<style scoped></style>

认识Store

  • 什么是Store
    • 一个store(如pinia)是一个实体(通过defineStore()创建 ),它会持有组件树种的 状态和业务逻辑(业务逻辑主要是网络请求等内容),也就是保存了全局的状态
    • 有点像始终存在,并且 每个人都可以读取和写入的组件
    • 可以在项目种,定义 任意数量的Store来管理状态
  • Stroe有三个核心概念
    • state、getters、actions
    • 等同于组件的 data、computed、methods
    • 一旦 store被实例化,可以直接在store上访问 state、getters、actions种定义的任何属性

定义一个store

在上面的例子中有讲过store的定义

  • 使用 defineStore 进行定义
    • 第一个参数:是store的唯一名称,也成为id,是必要的
    • 第二个参数是具体的store对象
  • 返回的函数同一使用useX进行命名
js 复制代码
import { defineStore } from "pinia";

//defineStore创建store,可以创建多个store
//第一个参数是用于命名store的
//第二个参数是store的具体内容
const useCounter = defineStore("counter", {
  state: () => ({
    count: 199,
  }),
});

//返回值是一个函数,将函数暴露出去
export default useCounter;

认识和定义State

  • state是store的核心部分
js 复制代码
import { defineStore } from "pinia";

//defineStore创建store,可以创建多个store
//第一个参数是用于命名store的
//第二个参数是store的具体内容
const useCounter = defineStore("counter", {
  state: () => ({
    count: 199,
  }),
});

//返回值是一个函数,将函数暴露出去
export default useCounter;

操作State

  • 读取和写入state:
    • 默认情况下,可以通过store实例访问状态来直接读取和写入状态
js 复制代码
//引入暴露的store函数
import useCounter from "./store/counter.js";
const counterStore = useCounter();

//读取
counterStore.count
//修改
counterStore.count++
  • 重置State
    • 可以通过调用store上的**$reset()**方法讲状态重置到初始值
js 复制代码
//引入暴露的store函数
import useCounter from "./store/counter.js";
const counterStore = useCounter();

counterStore.$reset()//会将counter恢复到初始定义的状态
  • 一次性修改多个State
    • 通过 $patch
js 复制代码
//引入暴露的store函数
import useCounter from "./store/counter.js";
const counterStore = useCounter();

counterStore.$patch({
    name:"zhangcheng",
    age:"18"
})
  • 替换state
    • 通过 $state方法进行替换
js 复制代码
//引入暴露的store函数
import useCounter from "./store/counter.js";
const counterStore = useCounter();

counterStore.$state = {
    name:"zhangcheng",
    age:"18"
}

认识和定义Getters

  • 基本使用,获取本store实例下的state
js 复制代码
import { defineStore } from "pinia";


const useCounter = defineStore("counter", {
  state: () => ({
    count: 199,
  }),
  getters:{
      doubleCount(state){
          //通过传参的方式进行访问
          return state.count
      },
      doubleCountAddOne(){
          //可以通过this进行访问
          return this.count*2+1
      }
  }
});

//返回值是一个函数,将函数暴露出去
export default useCounter;

//使用方法同state,先引入暴露的函数,执行,通过.的方式进行访问
  • 使用getters中的数据
    • 可以通过 this直接访问
js 复制代码
import { defineStore } from "pinia";


const useCounter = defineStore("counter", {
  state: () => ({
    count: 199,
  }),
  getters:{
      doubleCount(state){
          //通过传参的方式进行访问
          return state.count
      },
      doubleCountAddOne(){
          //可以通过this访问getters中的变量
          return this.doubleCount+1
      }
  }
});

//返回值是一个函数,将函数暴露出去
export default useCounter;
  • 用到别的store中的数据
js 复制代码
import { defineStore } from "pinia";
//引入其他的store
import userInfo from "./store/user.js";

const useCounter = defineStore("counter", {
  state: () => ({
    count: 199,
  }),
  getters:{
      getMessage(){
          //实例化而后使用
          const userStore = userInfo()
    		
          return userInfo.name + count
      }
  }
});

//返回值是一个函数,将函数暴露出去
export default useCounter;

认识和定义Actions

  • Actions相当于组件中的methods
  • 与getters一样,可以通过this访问store中的变量,但是没有传入state参数
js 复制代码
import { defineStore } from "pinia";
//引入其他的store
import userInfo from "./store/user.js";

const useCounter = defineStore("counter", {
  state: () => ({
    count: 199,
  }),
	actions:{
        countAdd(num){
            //可以传入参数
            //直接通过this进行访问state中的状态
            this.count += num
        }
    }
});


//具体使用
//引入暴露的store函数
import useCounter from "./store/counter.js";
const counterStore = useCounter();

//直接调用方法即可
counterStore.countAdd(10)

执行异步操作

js 复制代码
import { defineStore } from "pinia";
//引入其他的store
import userInfo from "./store/user.js";

const useCounter = defineStore("counter", {
	actions:{
      async getData(){
          const res = await fetch(xxxx)
          const data = await res.json()
          //改变state状态
          this.list = data
          //返回data
          retrun data
      }
    }
});
相关推荐
小龙几秒前
【开源项目】航空订票系统(界面 + 数据库 + 运行手册)开源说明
前端·航空订票系统
简单Janeee7 分钟前
[Vue 3 从零到上线]-第三篇:网页的指挥官——指令系统 (v-if, v-for, v-bind, v-on)
前端·javascript·vue.js
李元_霸10 分钟前
前端监控实践
前端·性能优化
星火开发设计11 分钟前
虚析构函数:解决子类对象的内存泄漏
java·开发语言·前端·c++·学习·算法·知识
前端程序猿i16 分钟前
第 7 篇:性能优化 —— 大量消息下的流畅体验
前端·vue.js·性能优化
object not found24 分钟前
UniCloud 本地调试云对象报 Cannot find module ‘uni-id-common‘ 的排查与解决
前端
用户982361079027727 分钟前
Vite + Rollup 打包分包陷阱:依赖版本冲突与状态隔离问题
前端框架
跨境小技27 分钟前
2026 Shopee数据抓取逐步教程:技术难点、解决思路与实战方法
前端·数据库·网络爬虫
一枚小太阳30 分钟前
想学 Electron?这份「能跑的示例集」一篇搞懂
前端·electron
是Dream呀31 分钟前
自动化打造信息影响力:用 Web Unlocker 和 n8n 打造你的自动化资讯系统
运维·前端·爬虫·自动化