Can Pinia replace Vuex as a more powerful state management tool?

prologue

Pinia is a brand new state management library developed specifically for Vue by members of the Vue.js team. It is also equivalent to vuex5. Do you think the following proposal about vuex5 looks very similar?

Vuex5 proposal

image.png

Pinia and Vuex functions

Vuex : State, Getters, Mutations(synchronous), Actions(asynchronous)

Pinia : State, Getters, Actions(supports both synchronous and asynchronous)

The latest version of vuex is 4.x

  • The use of vuex4 against vue3
  • The use of vuex3 against vue2

The latest version of pinia is 2.x

  • Applicable to vue2 and also supports vue3

the difference

  • Pinia has no mutations, and the usage of actions is different (pinia supports synchronous and asynchronous), but the usage of getters is consistent.

  • Pinia does not have a general outlet and is all modular. You need to define the module name. When multiple modules need to collaborate, you need to introduce multiple modules. Vuex has a general outlet. When using modularization, you do not need to introduce multiple modules.

  • Pinia does not need to go through other APIs when modifying the status, while vuex needs to be modified through commit and dispatch.

Installation and use of pinia

Install Pinia

Install Pinia using npm or yarn:

npm install pinia
# 或者
yarn add pinia

Create Pinia Store

Create a Pinia store in your project by creating a .tsfile. For example, you can create a store.tsfile named:

import { defineStore } from 'pinia';

export const useMyStore = defineStore('myStore', {
  state: () => ({
    count: 0,
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++;
    },
  },
});

In this example, we create a myStorePinia store named , which contains a state variable count, a getter doubleCount, and an action increment.

Register Pinia

In your application's entry point file (usually main.ts), register Pinia:

import { createApp } from 'vue';
import App from './App.vue';
import { createPinia } from 'pinia';

const app = createApp(App);

const pinia = createPinia();
app.use(pinia);

app.mount('#app');

Using Pinia Store in Vue components

Introduce in your Vue component useMyStoreand use it to access state, call operations, etc.:

<template>
  <div>
    <p>Count: {
   
   { count }}</p>
    <p>Double Count: {
   
   { doubleCount }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script>
import { defineComponent } from 'vue';
import { useMyStore } from './store';

export default defineComponent({
  setup() {
    const myStore = useMyStore();

    const count = myStore.count;
    const doubleCount = myStore.doubleCount;

    const increment = () => {
      myStore.increment();
    };

    return { count, doubleCount, increment };
  },
});
</script>

Advantages and disadvantages of vuex and pinia

Advantages of Pinia

  • Pinia allows you to modify your store without reloading the page.
  • Pinia is designed for TypeScript and provides strong typing support to catch more errors during development and make the code more maintainable and readable.
  • Pinia provides devtool support, which helps enhance the developer experience using the tool.
  • There are only state, getter, and action in pinia, and Mutation in Vuex is abandoned.
  • There is no need to create nested modules. If there is too much data in Vuex, we usually manage it in modules. In Pinia, each store is independent and does not affect each other.
  • The size is very small, only about 1KB
  • pinia supports plug-ins to extend its functions
  • Support server-side rendering
  • Pinia cum Vue 2 和 Vue 3.

Disadvantages of Pinia

  • Compared to Vuex, it doesn't have huge community support and solutions.
  • Pinia does not support debugging features such as time travel and editing.

Advantages of Vuex

  • Vuex has mutations, getters and actions.
  • Vuex has great community support compared to Pinia.
  • Vuex supports debugging features such as time travel and editing.

Disadvantages of Vuex

  • It's not TypeScript friendly.
  • You can only use it for large spas.

Implement local storage

Install plugin

pinia-plugin-persistRequires plugins and Pinia to be installed :

npm install pinia pinia-plugin-persist
# 或者
yarn add pinia pinia-plugin-persist

Create Pinia Store

Create a Pinia store to manage the state that needs to be persisted.

// store.js
import { defineStore } from 'pinia';
import { usePersist } from 'pinia-plugin-persist';

export const useMyStore = defineStore({
  id: 'myStore',
  state: () => ({
    count: 0,
  }),
  actions: {
    increment() {
      this.count++;
    },
  },
});

// 使用插件进行状态持久化
usePersist(useMyStore, {
  // 配置选项
  // 默认存储在 localStorage
  // 如果需要使用 sessionStorage,可以指定 storage: 'sessionStorage'
  key: 'myStore', // 存储的键名
  // 可以添加更多配置选项,例如过期时间
});

Using pinia-plugin-persistplugins, you can easily persist state without having to manually deal with local storage. You can configure more options as needed, such as setting an expiration time or custom storage keys. This helps simplify state management and data persistence.

Selection scenarios between vuex and pinia

Pinea is lightweight and small, making it suitable for small to medium-sized applications. It is also suitable for low complexity Vue.js projects as some debugging features like time travel and editing are still not supported.

Vuex is overkill for small and medium-sized Vue.js projects because it is heavyweight and has a large impact on performance degradation. Therefore, Vuex is suitable for large-scale, high-complexity Vue.js projects

Guess you like

Origin blog.csdn.net/weixin_40808668/article/details/132632877