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

Tutorial on installing and using virtualenv in Deepin

virtualenv is a tool for creating isolated Python...

Web Design: When the Title Cannot Be Displayed Completely

<br />I just saw the newly revamped ChinaUI....

A brief discussion on VUE uni-app conditional coding and page layout

Table of contents Conditional compilation Page La...

MySQL Quick Data Comparison Techniques

In MySQL operation and maintenance, a R&D col...

A brief analysis of kubernetes controllers and labels

Table of contents 01 Common controllers in k8s RC...

Solve the problem of combining AND and OR in MySQL

As shown below: SELECT prod_name,prod_price FROM ...

Detailed tutorial on installing Python 3.6.6 from scratch on CentOS 7.5

ps: The environment is as the title Install possi...

Implementation of mysql configuration SSL certificate login

Table of contents Preface 1. MySQL enables SSL co...

How to install docker using YUM

As shown in the following figure: If the version ...

js to achieve interesting countdown effect

js interesting countdown case, for your reference...

New ideas for time formatting in JavaScript toLocaleString()

Table of contents 1. Conventional ideas for time ...

react-beautiful-dnd implements component drag and drop function

Table of contents 1. Installation 2.APi 3. react-...

How to modify the default storage engine in MySQL

mysql storage engine: The MySQL server adopts a m...