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

MySQL master-slave replication principle and practice detailed explanation

Table of contents Introduction effect principle f...

Vue implements a movable floating button

This article example shares the specific code of ...

Linux concurrent execution is simple, just do it this way

Concurrency Functions time for i in `grep server ...

Alibaba Cloud Centos7.3 installation mysql5.7.18 rpm installation tutorial

Uninstall MariaDB CentOS7 installs MariaDB instea...

Some tips on using the HTML title attribute correctly

If you want to hide content from users of phones, ...

How to configure user role permissions in Jenkins

Jenkins configuration of user role permissions re...

Some wonderful uses of URL objects in JavaScript

Table of contents Preface Parsing parameters Modi...

How to implement blank space in Taobao with CSS3

Make a blank space for Taobao: When you shrink th...

Example of implementing the Graphql interface in Vue

Note: This article is about the basic knowledge p...

How to use Flex layout to achieve scrolling of fixed content area in the head

The fixed layout of the page header was previousl...

Summary of methods for inserting videos into HTML pages

Now if you want to use the video tag in a page, y...

JavaScript example code to determine whether a file exists

1. Business Scenario I have been doing developmen...

Example code for converting http to https using nginx

I am writing a small program recently. Because th...

Detailed explanation of nginx request header data reading process

In the previous article, we explained how nginx r...