Pitfall notes of vuex and pinia in vue3

Pitfall notes of vuex and pinia in vue3

introduce

Pinia is a lightweight state management library for Vue.js that has become very popular recently. It uses the new reactivity system in Vue 3 to build an intuitive and fully typed state management library.

Pinia's success can be attributed to its unique features for managing stored data (scalability, storage module organization, grouping of state changes, multi-store creation, etc.).

On the other hand, Vuex is also a popular state management library built for the Vue framework, and it is also the state management library recommended by the Vue core team. Vuex focuses heavily on application scalability, developer ergonomics, and confidence. It is based on the same flow architecture as Redux.

Installation and Usage

Install vuex

npm install vuex@next --save

cnpm install vuex@next --save-

yarn add vuex@next --save

Install pinia

npm install pinia@next

cnpm install pinia@next

yarn add pinia@next

After installation, just use it according to the following writing method. As long as you can use vuex, you can use the basic usage of pinia. The writing method of pinia plug-in is not shown here.

Simple comparison of writing differences and similarities

Vuex and pinia are written by the same team members, but pinia is more user-friendly and simpler.

How to write and use vuex in vue3

//store.js
import { createStore } from 'vuex'

export default createStore({
    // define data state: { a:1 },
    // define method mutations: {
        xxx(state,number){
            state.a = number
        }
    },
    // Asynchronous method actions: { },
    // Get data getters: { getA:state=>return state.a }
})

// Using <template> in vue3
    <div>
        {{number}}
        <button @click="clickHandle">Button</button>
    </div>
</template>
<script>
import {useStore} from "vuex"
export default {
    setup(){
        let store = useStore()
        // ⭐⭐⭐ If you directly get the value of state, you must use computed to achieve data responsiveness. If you directly get store.state.a, you will not monitor data changes. Or use getter, you don't need to use computed
        let number = computed(()=>store.state.a)
        const clickHandle = () => {
            store.commit("xxx","100")
        }
        return{number,clickHandle}
    }
}
<script>

How to write and use pinia in vue3

//store.js
import { defineStore } from 'pinia'

// defineStore returns a function after calling it, call this function to get the Store entity export const GlobalStore = defineStore({
  // id: required, unique among all Stores id: "myGlobalState",
  // state: function that returns an object state: () => ({
    a: 1,
  }),
  getters: {},
  actions: {
    setXXX(number) {
      this.a = number;
    },
  },
});

// Using <template> in vue3
    <div>
        {{number}}
        <button @click="clickHandle">Button</button>
    </div>
</template>
<script>
import {GlobalStore} from "@/store/store.js"
export default {
    setup(){
        let store = GlobalStore();
        // ⭐⭐⭐ If you directly get the value of state, you must use computed to achieve data responsiveness. If you directly get store.state.a, you will not monitor data changes. Or use getter, you don't need to use computed (this is the same as vuex)
        let number = computed(()=>store.a)
        const clickHandle = () => {
            store.setXXX("100")
        }
        return{number,clickHandle}
    }
}
<script>

From the comparison of these two codes, we can see that using pinia is more concise and lightweight. pinia cancels the original mutations and merges them into actions. When getting a value, we can directly click on the value without using .state. The same is true for methods.

Pros and Cons of Vuex and Pinia

Advantages of Vuex

  • Supports debugging features such as time travel and editing
  • Suitable for large, complex Vue.js projects

Disadvantages of Vuex

  • Starting from Vue 3, getter results are not cached like computed properties
  • Vuex 4 has some issues related to type safety

Advantages of Pinia

  • Full TypeScript support: It is easier to add TypeScript than to add it in Vuex
  • Extremely lightweight (about 1KB)
  • Store actions are dispatched as regular function calls instead of using the dispatch method or MapAction helper, which is common in Vuex
  • Support multiple stores
  • Support Vue devtools, SSR and webpack code splitting

Disadvantages of Pinia

  • Does not support debugging features such as time travel and editing

When to use Pinia and when to use Vuex

From my personal experience, since Pinea is lightweight and small in size, it is suitable for small to medium applications. It is also suitable for low-complexity Vue.js projects, as some debugging features like time travel and editing are still not supported.

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

Summarize

This is the end of this article about the pitfalls of vuex and pinia in vue3. For more relevant vue3 vuex and pinia pitfalls, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue state management: using Pinia instead of Vuex
  • A detailed introduction to Pinia, a new member of the Vue ecosystem
  • Getting Started with Vue's New State Management Library Pinia
  • Still using vuex? Learn about pinia
  • Practical record of pitfalls with Vue3 and Pinia
  • Getting Started Tutorial on Pinia for Vue3 State Management

<<:  Docker custom network container interconnection

>>:  Manual and scheduled backup steps for MySQL database

Recommend

How to change the system language of centos7 to simplified Chinese

illustrate When you install the system yourself, ...

How to modify the length limit of group_concat in Mysql

In MySQL, there is a function called "group_...

Vue mobile terminal determines the direction of finger sliding on the screen

The vue mobile terminal determines the direction ...

This article will show you how JavaScript garbage collection works

Table of contents 1. Overview 2. Memory Managemen...

Basic knowledge of HTML: a preliminary understanding of web pages

HTML is the abbreviation of Hypertext Markup Langu...

CSS sets the list style and creates the navigation menu implementation code

1. Set the list symbol list-style-type: attribute...

How to use boost.python to call c++ dynamic library in linux

Preface Recently I started using robot framework ...

Why TypeScript's Enum is problematic

Table of contents What happened? When to use Cont...

How to create Baidu dead link file

There are two types of dead link formats defined b...

How to set up scheduled backup tasks in Linux centos

Implementation Preparation # Need to back up the ...

A brief introduction to the simple use of CentOS7 firewall and open ports

Overview (official has more detailed description)...

CSS3 transition to achieve underline example code

This article introduces the sample code of CSS3 t...

Detailed example of using if statement in mysql stored procedure

This article uses an example to illustrate the us...