Home > Web Front-end > Vue.js > body text

Let's talk about the differences in design and implementation between Vuex and Pinia

青灯夜游
Release: 2022-12-07 18:24:37
forward
2698 people have browsed it

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>
Copy after login

Combined API setup Syntactic sugar:

<script setup>
import { reactive } from &#39;Vue&#39;
// 状态 state
const state = reactive({
  count: 0
})
// 动作 action
const increment = () => {
  state.count++
}
</script>
// 视图 view
<template> {{ state.count }} </template>
Copy after login

Lets talk about the differences in design and implementation between Vuex and Pinia

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)
1. If the communication is between adjacent parent and child components, you can use props In the emit method, the parent component passes in data through the props of the child component, and triggers some methods of the parent component through the emit method inside the child component.

Lets talk about the differences in design and implementation between Vuex and Pinia

2. If it is not directly adjacent, but has a nested relationship with many layers in between, then you can use the provide inject method, and the high-level component throws status and Actions, low-level components receive usage data and trigger actions.

Lets talk about the differences in design and implementation between Vuex and Pinia

#If the two components of the target are not on the same component chain, a possible solution is "state promotion".

You can store the common state in the minimum common ancestor component of the two, and then communicate through the above two methods.

    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 latter is more concise to write code and less prone to errors.

This can already solve the problems in most scenarios. So what unique capabilities can state management tools outside the framework provide?

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。

Lets talk about the differences in design and implementation between Vuex and Pinia

整个数据流动关系为:

1、view 视图中的交互行为会创建 action,交由 dispatcher 调度器。

2、dispatcher 接收到 action 后会分发至对应的 store。

3、store 接收到 action 后做出响应动作,并触发 change 事件,通知与其关联的 view 重新渲染内容。

这就是 Flux 架构最核心的特点:单向数据流

与传统的 MVC 架构相比,单向数据流也带来了一个好处:可预测性

所有对于状态的修改都需要经过 dispatcher 派发的 action 来触发的,每一个 action 都是一个单独的数据对象实体,可序列化,操作记录可追踪,更易于调试。

Vuex 与 Pinia 大体上沿用 Flux 的思想,并针对 Vue 框架单独进行了一些设计上的优化。

Vuex

Lets talk about the differences in design and implementation between Vuex and Pinia

  • ? state:整个应用的状态管理单例,等效于 Vue 组件中的 data,对应了 Flux 架构中的 store。
  • ? getter:可以由 state 中的数据派生而成,等效于 Vue 组件中的计算属性。它会自动收集依赖,以实现计算属性的缓存。
  • ? mutation:类似于事件,包含一个类型名和对应的回调函数,在回调函数中可以对 state 中的数据进行同步修改。
    • Vuex 不允许直接调用该函数,而是需要通过 store.commit 方法提交一个操作,并将参数传入回调函数。
    • commit 的参数也可以是一个数据对象,正如 Flux 架构中的 action 对象一样,它包含了类型名 type 和负载 payload
    • 这里要求 mutation 中回调函数的操作一定是同步的,这是因为同步的、可序列化的操作步骤能保证生成唯一的日志记录,才能使得 devtools 能够实现对状态的追踪,实现 time-travel。
  • ? action:action 内部的操作不受限制,可以进行任意的异步操作。我们需要通过 dispatch 方法来触发 action 操作,同样的,参数包含了类型名 type 和负载 payload
    • action 的操作本质上已经脱离了 Vuex 本身,假如将它剥离出来,仅仅在用户(开发者)代码中调用 commit 来提交 mutation 也能达到一样的效果。
  • ? module:store 的分割,每个 module 都具有独立的 state、getter、mutation 和 action。
    • 可以使用 module.registerModule 动态注册模块。
    • 支持模块相互嵌套,可以通过设置命名空间来进行数据和操作隔离。

Vuex 中创建 store

import { createStore } from &#39;Vuex&#39;
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(&#39;increment&#39;);
    },
    plusAsync(context) {
      setTimeout(() => { context.commit(&#39;increment&#39;, 2); }, 2000)
    }
  }
})
Copy after login

与 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 &#39;Vuex&#39;;
const vuex = useVuexStore();
</script>

<template>
  <div>
    <div> count: {{ vuex.state.count }} </div>

    <button @click="() => {
      vuex.dispatch(&#39;plus&#39;)
    }">点击这里加1</button>

    <button @click="() => {
      vuex.dispatch(&#39;plusAsync&#39;)
    }">异步2s后增加2</button>

    <div> double: {{ vuex.getters.double }}</div>
  </div>
</template>
Copy after login

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 &#39;Pinia&#39;
export const useStore = defineStore(&#39;main&#39;, {
  state: () => {
    return {
      count: 0
    }
  },
  getters: {
    double: (state) => {
      return state.count * 2;
    }
  },
  actions: {
    increment() {
      this.count++;
    },
    asyncIncrement(num = 1) {
      setTimeout(() => {
        this.count += num;
      }, 2000);
    }
  }
})
Copy after login

Pinia 组件内使用

可直接读写 state,直接调用 action 方法。

<script setup>
import { useStore as usePiniaStore } from &#39;../setup/Pinia&#39;;
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>
Copy after login

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
  })
})
Copy after login

一些实现细节


Vuex 中的 commit 方法

commit (_type, _payload, _options) {
// 格式化输入参数
// commit 支持 (type, paload),也支持对象风格 ({ type: &#39;&#39;, ...})
  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))
}
Copy after login

在使用 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)
    })
  })
}
Copy after login

从这两个方法的实现中也可以看出 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([&#39;increment&#39;]), // 将 this.increment 映射到 this.$store.commit(&#39;increment&#39;)
    ...mapActions({
      add: &#39;incremnet&#39;  // 传入对象类型,实现重命名的映射关系
    })
  }
}
Copy after login

在 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)
  }
}
Copy after login

为了使代码更容易维护,结构更清晰,通常会将对于状态的修改操作与状态本身放在同一个组件内部。提供方可以抛出一个响应式的 ref 数据以及对其进行操作的方法,接收方通过调用函数对状态进行修改,而非直接操作状态本身。同时,提供方也可以通过 readonly 包裹状态以禁止接收方的直接修改操作。

(学习视频分享:web前端开发编程基础视频

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!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!