


Let's talk about the differences in design and implementation between Vuex and Pinia
When developing front-end projects, state management is always an unavoidable topic. Vue and the React framework itself provide some capabilities to solve it this problem. However, there are often other considerations when developing large-scale applications, such as the need for more standardized and complete operation logs, time travel capabilities integrated in developer tools, server-side rendering, etc. This article takes the Vue framework as an example to introduce the differences in the design and implementation of the two state management tools, Vuex and Pinia.
Vue state management
First of all, let’s introduce the state management method provided by the Vue framework itself. [Related recommendations: vuejs video tutorial, web front-end development]
The Vue component mainly involves three components: state, action and view.
In the optional API, a state object is returned through the data
method, and the action to modify the state is set through the methods
method.
If you use the combined API setup syntax sugar, the state is generated through the reactive
method, and the action only needs to be defined as a normal function or arrow function.
Optional API:
<script> export default { data() { // 状态 state return { count: 0 } }, methods() { // 动作 action increment() { this.count++ } } } </script> // 视图 view <template> {{ count }} </template>
Combined API setup Syntactic sugar:
<script setup> import { reactive } from 'Vue' // 状态 state const state = reactive({ count: 0 }) // 动作 action const increment = () => { state.count++ } </script> // 视图 view <template> {{ state.count }} </template>
The view is generated by the state, and the operation can modify the state.
If a certain part of the page can be isolated into an independent entity composed of states, views, and actions that are decoupled from the outside world, then the state management method within the component provided by Vue is enough.
But these two situations are often encountered in development:
- Multiple page components rely on the same state.
- Different interactive behaviors within multiple page components need to modify the same state.
For example, if we want to create a theme customization function, we need to obtain the color parameters in the interface at the project entrance, and then use this data in many pages of the entire project.
One way is to use CSS variables, define some CSS variables on the top-level root element of the page, use var()
in Sass to initialize a Sass variable, which is referenced by all pages Just this variable. To obtain the interface data at the project entrance, you need to manually modify the css variables on the root element.
In Vue, the framework provides a v-bind way to write css. We can consider storing all color configurations in a unified store.
When encountering these two situations, we usually solve them through communication between components, such as:
- For adjacent parent-child components:
props/emit
defineProps({})
defineEmits(['change', '...'])
- For multi-level nesting:
provide/inject
- ##provide(name: string | symbol, value: any)
- inject(name: string | symbol, defaultValue: any)
- ##provide(name: string | symbol, value: any)
- The former: the public ancestor component stores the state, and passes the responsive state and its associated operations to the sub-components step by step through props.
- The latter: the common ancestor serves as the provider, and multiple descendant components serve as injectors to obtain data and operate data.
The core ideas and usage of Vuex and Pinia
##Flux architecture
Flux 是 Facebook 在构建大型 Web 应用程序时为了解决数据一致性问题而设计出的一种架构,它是一种描述状态管理的设计模式。绝大多数前端领域的状态管理工具都遵循这种架构,或者以它为参考原型。
Flux 架构主要有四个组成部分:
- ? store:状态数据的存储管理中心,可以有多个,可以接受 action 做出响应。
- ? view:视图,根据 store 中的数据渲染生成页面,与 store 之间存在发布订阅关系。
- ? action:一种描述动作行为的数据对象,通常会包含动作类型 type 和需要传递的参数 payload 等属性。
- ? dispatcher:调度器,接收 action 并分发至 store。
整个数据流动关系为:
1、view 视图中的交互行为会创建 action,交由 dispatcher 调度器。
2、dispatcher 接收到 action 后会分发至对应的 store。
3、store 接收到 action 后做出响应动作,并触发 change 事件,通知与其关联的 view 重新渲染内容。
这就是 Flux 架构最核心的特点:单向数据流。
与传统的 MVC 架构相比,单向数据流也带来了一个好处:可预测性。
所有对于状态的修改都需要经过 dispatcher 派发的 action 来触发的,每一个 action 都是一个单独的数据对象实体,可序列化,操作记录可追踪,更易于调试。
Vuex 与 Pinia 大体上沿用 Flux 的思想,并针对 Vue 框架单独进行了一些设计上的优化。
Vuex
- ? state:整个应用的状态管理单例,等效于 Vue 组件中的 data,对应了 Flux 架构中的 store。
- ? getter:可以由 state 中的数据派生而成,等效于 Vue 组件中的计算属性。它会自动收集依赖,以实现计算属性的缓存。
- ? mutation:类似于事件,包含一个类型名和对应的回调函数,在回调函数中可以对 state 中的数据进行同步修改。
- Vuex 不允许直接调用该函数,而是需要通过
store.commit
方法提交一个操作,并将参数传入回调函数。 - commit 的参数也可以是一个数据对象,正如 Flux 架构中的 action 对象一样,它包含了类型名
type
和负载payload
。 - 这里要求 mutation 中回调函数的操作一定是同步的,这是因为同步的、可序列化的操作步骤能保证生成唯一的日志记录,才能使得 devtools 能够实现对状态的追踪,实现 time-travel。
- Vuex 不允许直接调用该函数,而是需要通过
- ? action:action 内部的操作不受限制,可以进行任意的异步操作。我们需要通过
dispatch
方法来触发 action 操作,同样的,参数包含了类型名type
和负载payload
。- action 的操作本质上已经脱离了 Vuex 本身,假如将它剥离出来,仅仅在用户(开发者)代码中调用
commit
来提交 mutation 也能达到一样的效果。
- action 的操作本质上已经脱离了 Vuex 本身,假如将它剥离出来,仅仅在用户(开发者)代码中调用
- ? module:store 的分割,每个 module 都具有独立的 state、getter、mutation 和 action。
- 可以使用
module.registerModule
动态注册模块。 - 支持模块相互嵌套,可以通过设置命名空间来进行数据和操作隔离。
- 可以使用
Vuex 中创建 store
import { createStore } from 'Vuex' export default createStore({ state: () => { return { count: 0 } }, mutations: { increment(state, num = 1) { state.count += num; } }, getters: { double(state) { return state.count * 2; } }, actions: { plus(context) { context.commit('increment'); }, plusAsync(context) { setTimeout(() => { context.commit('increment', 2); }, 2000) } } })
与 Vue 选项式 API 的写法类似,我们可以直接定义 store 中的 state、mutations、getters、actions。
其中 mutations、getters 中定义的方法的第一个参数是 state,在 mutation 中可以直接对 state 同步地进行修改,也可以在调用时传入额外的参数。
actions 中定义的方法第一个参数是 context,它与 store 具有相同的方法,比如 commit、dispatch 等等。
Vuex 在组件内使用
通过 state、getters 获取数据,通过 commit、dispatch 方法触发操作。
<script setup> import { useStore as useVuexStore } from 'Vuex'; const vuex = useVuexStore(); </script> <template> <div> <div> count: {{ vuex.state.count }} </div> <button @click="() => { vuex.dispatch('plus') }">点击这里加1</button> <button @click="() => { vuex.dispatch('plusAsync') }">异步2s后增加2</button> <div> double: {{ vuex.getters.double }}</div> </div> </template>
Pinia
保留:
- ? state:store 的核心,与 Vue 中的 data 一致,可以直接对其中的数据进行读写。
- ? getters:与 Vue 中的计算属性相同,支持缓存。
- ? actions:操作不受限制,可以创建异步任务,可以直接被调用,不再需要 commit、dispatch 等方法。
舍弃:
- ? mutation:Pinia 并非完全抛弃了 mutation,而是将对 state 中单个数据进行修改的操作封装为一个 mutation,但不对外开放接口。可以在 devtools 中观察到 mutation。
- ? module:Pinia 通过在创建 store 时指定 name 来区分不同的 store,不再需要 module。
Pinia 创建 store
import { defineStore } from 'Pinia' export const useStore = defineStore('main', { state: () => { return { count: 0 } }, getters: { double: (state) => { return state.count * 2; } }, actions: { increment() { this.count++; }, asyncIncrement(num = 1) { setTimeout(() => { this.count += num; }, 2000); } } })
Pinia 组件内使用
可直接读写 state,直接调用 action 方法。
<script setup> import { useStore as usePiniaStore } from '../setup/Pinia'; const Pinia = usePiniaStore(); </script> <template> <div> <div> count: {{ Pinia.count }}</div> <button @click="() => { Pinia.count++; }">直接修改 count</button> <button @click="() => { Pinia.increment(); }">调用 action</button> <button @click="() => { Pinia.asyncIncrement(); }">调用异步 action</button> <div> double: {{ Pinia.double }}</div> </div> </template>
1、对 state 中每一个数据进行修改,都会触发对应的 mutation。
2、使用 action 对 state 进行修改与在 Pinia 外部直接修改 state 的效果相同的,但是会缺少对 action 行为的记录,如果在多个不同页面大量进行这样的操作,那么项目的可维护性就会很差,调试起来也很麻烦。
Pinia 更加灵活,它把这种选择权交给开发者,如果你重视可维护性与调试更方便,那就老老实实编写 action 进行调用。
如果只是想简单的实现响应式的统一入口,那么也可以直接修改状态,这种情况下只会生成 mutation 的记录。
Pinia action
Pinia 中的 action 提供了订阅功能,可以通过 store.$onAction()
方法来设置某一个 action 方法的调用前、调用后、出错时的钩子函数。
Pinia.$onAction(({ name, // action 名称 store, args, // action 参数 after, onError }) => { // action 调用前钩子 after((result) => { // action 调用后钩子 }) onError((error) => { // 出错时钩子,捕获到 action 内部抛出的 error }) })
一些实现细节
Vuex 中的 commit 方法
commit (_type, _payload, _options) { // 格式化输入参数 // commit 支持 (type, paload),也支持对象风格 ({ type: '', ...}) const { type, payload, options } = unifyObjectStyle(_type, _payload, _options) const mutation = { type, payload } const entry = this._mutations[type] this._withCommit(() => { entry.forEach(function commitIterator (handler) { handler(payload) }) }) this._subscribers .slice() .forEach(sub => sub(mutation, this.state)) }
在使用 commit 时,可以直接传入参数 type 和 payload,也可以直接传入一个包含 type 以及其他属性的 option 对象。
Vuex 在 commit 方法内会先对这两种参数进行格式化。
Vuex 中的 dispatch 方法
dispatch (_type, _payload) { const { type, payload } = unifyObjectStyle(_type, _payload) const action = { type, payload } const entry = this._actions[type] // try sub.before 调用前钩子 try { this._actionSubscribers .slice() .filter(sub => sub.before) .forEach(sub => sub.before(action, this.state)) } catch (e) { // …… } // 调用 action,对于可能存在的异步请求使用 promiseAll 方式调用 const result = entry.length > 1 ? Promise.all(entry.map(handler => handler(payload))) : entry[0](payload) return new Promise((resolve, reject) => { result.then(res => { // …… try sub.after 调用后钩子 resolve(res) }, error => { // …… try sub.error 调用出错钩子 reject(error) }) }) }
从这两个方法的实现中也可以看出 mutations、actions 的内部实现方式。
所有的 mutations 放在同一个对象内部,以名称作为 key,每次 commit 都会获取到对应的值并执行操作。
actions 操作与 mutations 类似,但是增加了一个辅助的数据 actionSubscribers
,用于触发 action 调用前、调用后、出错时的钩子函数。
辅助函数 mapXXX
在 Vuex 中,每次操作都要通过 this.$store.dispatch()/commit()
。
如果想要批量将 store 中的 state、getters、mutations、actions 等映射到组件内部,可以使用对应的 mapXXX 辅助函数。
export default { computed: { ...mapState([]), ...mapGetters([]) }, methods: { ...mapMutations(['increment']), // 将 this.increment 映射到 this.$store.commit('increment') ...mapActions({ add: 'incremnet' // 传入对象类型,实现重命名的映射关系 }) } }
在 Pinia + 组合式 API 下,通过 useStore
获取到 store 后,可以直接读写数据和调用方法,不再需要辅助函数。
状态管理工具的优势
-
devtools 支持
- 记录每一次的修改操作,以时间线形式展示。
- 支持 time-travel,可以回退操作。
- 可以在不刷新页面的情况下实现对 store 内部数据的修改。
- Pinia 与 Vuex 相比
- 接口更简单,代码更简洁:
- 舍弃了 mutation,减少了很多不必要的代码。
- 可以直接对数据进行读写,直接调用 action 方法,不再需要 commit、dispatch。
- 更好的 TypeScript 支持:
- Vuex 中的很多属性缺少类型支持,需要开发者自行进行模块类型的声明。
- Pinia 中的所有内容都是类型化的,尽可能地利用了 TS 的类型推断。
- 接口更简单,代码更简洁:
最后
当项目涉及的公共数据较少时,我们可以直接利用 Vue 的响应式 API 来实现一个简单的全局状态管理单例:
export const createStore = () => { const state = reactive({ count: 0; }) const increment = () => { state.count++; } return { increment, state: readonly(state) } }
为了使代码更容易维护,结构更清晰,通常会将对于状态的修改操作与状态本身放在同一个组件内部。提供方可以抛出一个响应式的 ref 数据以及对其进行操作的方法,接收方通过调用函数对状态进行修改,而非直接操作状态本身。同时,提供方也可以通过 readonly 包裹状态以禁止接收方的直接修改操作。
The above is the detailed content of Let's talk about the differences in design and implementation between Vuex and Pinia. For more information, please follow other related articles on the PHP Chinese website!

Vue.js is loved by developers because it is easy to use and powerful. 1) Its responsive data binding system automatically updates the view. 2) The component system improves the reusability and maintainability of the code. 3) Computing properties and listeners enhance the readability and performance of the code. 4) Using VueDevtools and checking for console errors are common debugging techniques. 5) Performance optimization includes the use of key attributes, computed attributes and keep-alive components. 6) Best practices include clear component naming, the use of single-file components and the rational use of life cycle hooks.

Vue.js is a progressive JavaScript framework suitable for building efficient and maintainable front-end applications. Its key features include: 1. Responsive data binding, 2. Component development, 3. Virtual DOM. Through these features, Vue.js simplifies the development process, improves application performance and maintainability, making it very popular in modern web development.

Vue.js and React each have their own advantages and disadvantages, and the choice depends on project requirements and team conditions. 1) Vue.js is suitable for small projects and beginners because of its simplicity and easy to use; 2) React is suitable for large projects and complex UIs because of its rich ecosystem and component design.

Vue.js improves user experience through multiple functions: 1. Responsive system realizes real-time data feedback; 2. Component development improves code reusability; 3. VueRouter provides smooth navigation; 4. Dynamic data binding and transition animation enhance interaction effect; 5. Error processing mechanism ensures user feedback; 6. Performance optimization and best practices improve application performance.

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software