Vue state management: using Pinia instead of Vuex

Vue state management: using Pinia instead of Vuex

1. What is Pinia?

Pinia is a state management solution for vue , developed by members of the vuex team. It implements many vuex5 proposals, is more lightweight and has devtools support.

vuex4 has been criticized for its poor support for typescript , and vuex5 is also delayed.

So there was the emergence of Pina

Compared with vuex:

  • pinia does not need to create complex wrappers to support typescript . It naturally supports typescript type judgment, enjoys the automatic completion brought by IDE, reduces the mental burden of development, and reduces string-oriented programming in the Vue development process.
  • Removed the concept of mutations, leaving only the concepts of state , getters and anctions to reduce code redundancy
  • No need to add stores manually, the created stores will be automatically added when used
  • There is no concept of module . You don't have to face many modules nested under one store. Use a single file store (somewhat like a reducer in redux/toolkit) and you can directly import other stores for use

The Pinia documentation has this to say:

Pinia tries to stay as close to the philosophy of Vuex as possible. It was intended to test a proposal for the next iteration of Vuex, and it was successful as we currently have an open RFC for Vuex 5 with an API very similar to the one used by Pinia. Please note that I (Eduardo), the author of Pania, am part of the Vue.js core team and actively participated in the design of APIs such as Router and Vuex. My personal intention with this project was to redesign the experience of using a global Store while keeping Vue's approachable philosophy. I made Pania's API as close to Vuex as it moves forward so that people can easily migrate to Vuex or even merge the two projects (under Vuex) in the future.

So learning Pinia now is equivalent to learning Vuex5 in advance.

2. Pinia is easy to use

First, we initialize a vite+vue+ts project

pnpm create vite pinia-demo -- --template vue-ts

Install pinia

pnpm i pinia

Open the project, edit the main.ts file in the src directory, and import Pinia

//main.ts
​
import { createApp } from 'vue'
import App from './App.vue'
​
import { createPinia } from 'pinia'
​
createApp(App).use(createPinia()).mount('#app')

Create a store folder in the src directory to store state management, and then create a counter.ts . Let's make a simple counter state application

import { defineStore } from 'pinia'
​
export const useCounterStore = defineStore('counter', {
  state: () => {
    return {
      count: 0,
    }
  },
  getters: {
    doubleCount: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})

Pinia creates a store through the defineStore function, which receives an id to identify store and store options

We can also use a callback function to return options . The writing method in the callback function body is similar to setup() method of vue . For example, the definition above can be written as

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  function doubleCount() {
    return count.value * 2
  }
  function increment() {
    count.value++
  }
​
  return { count, increment }
})

Next we use store in App.vue

<script setup lang="ts">
import { useCounterStore } from './store/counter'
const useCounter = useCounterStore()
</script>
​
<template>
  <h2>{{ useCounter }}</h2>
  <h2>{{ useCounter.count }}</h2>
  <h2>{{ useCounter.doubleCount() }}</h2>
  <button @click="useCounter.increment">increment</button>
</template>
​
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

In the process of using Pinia , you can find that the automatic completion is quite excellent

The browser runs as follows:

Open the developer tools to view vue devtool

vue devtool supports adding, deleting, modifying and checking Pinia status!

Pinia has multiple ways to modify the state:

  • Use actions as shown above
  • Modify the state directly
const countPlus_1 = useCounter.count++

Use store 's $patch function, which supports both options and callback functions. The callback function is suitable for states that are arrays or other states that require calling state methods for modification.

const countPlus_2 = useCounter.$patch({ count: useCounter.count + 1 })

const countPlus_3 = useCounter.$patch((state) => state.count++)

The StoreToRefs function needs to be used for the state structure

const { count } = storeToRefs(useCounter)

3. User experience

Pinia is very user-friendly to learn and use. You can get started by reading the official documentation. During the process, you can clearly feel that it is faster than vuex and has an excellent coding experience.

For small projects, state management focuses more on convenience and speed (you may not even need it), so vuex is a little complicated. When vue3 was released in beta , some people said that you can use a combined api such as provide and inject to replace vuex , so the emergence of Pinia , a lightweight state management solution, is quite timely.

This is the end of this article about Vue state management using Pinia instead of Vuex. For more relevant content about using Pinia instead of Vuex, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • A detailed introduction to Pinia, a new member of the Vue ecosystem
  • Pitfall notes of vuex and pinia in vue3
  • 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

<<:  Common functions of MySQL basics

>>:  Web design dimensions and rules for advertising design on web pages

Recommend

VMware vsphere 6.5 installation tutorial (picture and text)

vmware vsphere 6.5 is the classic version of vsph...

Talking about Less and More in Web Design (Picture)

Less is More is a catchphrase for many designers....

Some thoughts and experience sharing on web page (website) design and production

First, before posting! Thanks again to I Want to S...

Introduction to MySQL overall architecture

The overall architecture of MySQL is divided into...

Three ways to align div horizontal layout on both sides

This article mainly introduces three methods of i...

Introducing the code checking tool stylelint to share practical experience

Table of contents Preface text 1. Install styleli...

mysql uses stored procedures to implement tree node acquisition method

As shown in the figure: Table Data For such a tre...

MySQL 8.0.22 winx64 installation and configuration method graphic tutorial

The database installation tutorial of MySQL-8.0.2...

How to add Nginx to system services in CentOS7

Introduction After compiling, installing and solv...

Detailed explanation of various join summaries of SQL

SQL Left Join, Right Join, Inner Join, and Natura...

Vue uses drag and drop to create a structure tree

This article example shares the specific code of ...

CSS multi-column layout solution

1. Fixed width + adaptive Expected effect: fixed ...

How to modify the "Browse" button of the html form to upload files

Copy code The code is as follows: <!DOCTYPE HT...