Pinia和Vuex有啥区别

Pinia和Vuex都是 Vue 状态管理库。但它们还是存在一些区别。

1.开发背景

1)Vuex:Vuex 是 Vue.js 官方推出的状态管理库,主要用于管理复杂应用中的全局状态。它在 Vue 2 和 Vue 3 中都被广泛使用。

2)Pinia:Pinia 是一个社区驱动的状态管理库,最初是为了弥补 Vuex 在某些场景下的不足而创建的。现在,它已经被 Vue 官方认可,并成为 Vue 3 推荐的状态管理库之一。

2.API

1)Vuex

使用 store 对象来管理状态。

通过 mapState、mapActions 等辅助函数来映射状态和操作。

使用 mutations 进行同步状态更新,actions 进行异步操作。

支持模块化,通过 modules 选项可以将状态分割成多个模块。

2)Pinia

引入了 Store 的概念,每个 Store 是一个独立的状态管理单元。

使用 defineStore 定义 Store,支持直接在 Store 中定义状态、 getters 和 actions。

状态更新可以直接在 actions 中进行,无需区分 mutations 和 actions。

同样支持模块化,但通过 Store 的组合来实现更灵活的状态管理。

3.使用方式

Vuex的使用方式

javascript 复制代码
//store/index.js
import { createStore } from 'vuex';
const store = createStore({
  state() {
    return { count: 0 };
  },
  // 定义Getter
  getters: {
    evenOrOdd: state => state.count % 2 === 0 ? 'even' : 'odd'
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  },
  actions: {
    incrementIfOdd(context) {
      context.commit('increment');
    }
  }
});

使用store,创建一个StoreUsed.vue组件

xml 复制代码
<template>
    <div>
     <p>Count: {{ count }}</p>
     <p>Even or Odd? {{ evenOrOdd }}</p>
     <button @click="increment">Increment</button>
     <button @click="incrementIfOdd">incrementIfOdd</button>    </div>
</template>
<script>
export default {
  computed: {
    count() {
      return this.$store.state.count
    },
    evenOrOdd () {
      return this.$store.getters.evenOrOdd
    }
  },
  methods: {
    increment() {
      this.$store.commit('increment')
    },
    incrementIfOdd () {
      this.$store.dispatch('incrementIfOdd')
    }
  }
}
</script>

Pinia的使用方式

创建 store/index.js 文件

javascript 复制代码
import { defineStore } from "pinia"
// defineStore(当前 store 的 Id, {配置项})
export const useCountStore = defineStore("count", {
  // 状态
  state: () => {
    return {
      count: 1
    }
  },
  // 计算属性
  getters: {
    // 这里的计算属性使用时,为一个属性而不是方法
    increaseNum(store) {
      return store.count * 10
    }
  },
  // 方法
  actions: {
    addCount(value) {
      this.count += value
    }
  }
})

在 main.js 中引入

javascript 复制代码
// 这是 Vue3 的引入方式,Vue2 不太一样
import { createApp } from "vue";
import App from "./App.vue";
import { createPinia } from "pinia";

const app = createApp(App);
app.use(createPinia());
app.mount("#app");

pinia基本使用

xml 复制代码
<script setup>
import { useCountStore } from "../store/index.js";

// 可以直接通过 store. 去获取 state、getters、actions 中的属性和方法了
const countStore = useCountStore();
// 直接获取
countStore.count // 1

// 计算属性获取
countStore.increaseNum // 10

// 修改状态1
countStore.count += 1

// 修改状态2
countStore.addCount(1)

// 修改状态3,这种方式和 React 中的 setState 很像
countStore.$patch({
  count: countStore.count + 1
})

// 修改状态4
countStore.$patch((state) => {
  state.count += 1
})

// 替换状态(不是覆盖状态),需要新的状态去替换旧的,如果 key 值不相同就是添加新状态
countStore.$state = {count: 2}

// 重置状态
countStore.$reset()


// store 中的值,每修改一次就会触发
countStore.$subscribe(({ events, storeId, type }, state) => {
  // 里面包含了一些信息
  events
   
  // 这个 store 的 Id,这里是 count
  storeId

  /*
	修改值的方式:
	  'direct':直接修改、使用 action 中的方式修改
	  'patch object':使用 $patch({}) 修改
	  'patch function':使用 $patch((state)=>{}) 修改、使用 $state 替换、$reset()重置
  */
  type
});


// action 中的函数每次调用,都会触发一次
countStore.$onAction(({ args, name, store, after, onError }) => {
  // 调用 actions 中函数的传参列表
  args

  // 函数名称
  name

  // store 对象
  store

  // 当函数正常执行完成后执行
  // result 接收函数返回成功状态的 Promise
  after((result) => {
    console.log(result);
  });

  // 当函数中存在失败状态的 Promise,或函数抛出异常时执行
  onError((err) => {
    console.log(err);
  });
});
</script>
相关推荐
RobinDevNotes34 分钟前
从 Electron 到 GPUI,9 个跨平台桌面方案该怎么选
前端·javascript·rust·electron·openresty·前端开发工具
jay神2 小时前
基于 YOLOv8 的轴承缺陷检测(Web 版)
前端·人工智能·yolo
jay神2 小时前
基于 YOLOv8 的森林火灾检测系统(Web 版)
前端·yolo
code2cat2 小时前
HTML基础篇之第一张网页:从index.html到浏览器里的任务清单
前端·html
miss3 小时前
AI 改完不敢上线?OpenSpec 规约驱动开发实战
前端·代码规范·前端工程化
AiMan3 小时前
腾讯ima还是不可以导出左侧所有对话,只能单条导出,方法不对吗
前端
去伪存真3 小时前
并发量一高就装死?Agent 全链路“防猝死”手册
前端·agent
Moment3 小时前
AI 编程时代,聊聊我的 Mac mini 双屏桌面
前端·后端
AiMan3 小时前
先确认能不能一次把Microsofat Copilot所有内容打包一个文件导出
前端
总要学点什么3 小时前
第97篇:三维数据加载-城市建筑白模自定义着色器——让一条光带沿高度扫上去,快慢却由帧率说了算
前端·gis·webgl·cesium·着色器·空间分析·白模