First, Pinia

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

Pinia’s success can be attributed to its unique ability to manage stored data (scalability, storage module organization, grouping of state changes, creation of multiple stores, and so on).

Pinia advantages:

  • Intuitive and easy to learn
  • Extremely light, only 1 KB
  • Modular design for easy separation of states
  • Pinia has no mutations, so state is unified in actions. Although Store can be directly operated by accessing the corresponding state through this.xx, it is still recommended to operate in actions to ensure that the state will not be changed by accident
  • Store actions are scheduled as regular function calls, rather than using the Dispatch method or MapAction helper functions, which is common in Vuex
  • Support for multiple stores
  • Support Vue DevTools, SSR and Webpack code splitting

Pinia faults:

  • Debugging functions such as time travel and editing are not supported

Two, install using Pinia

Open the terminal in the project root directory and enter the following command

Yarn add pinia@next # or with NPM NPM install pinia@next // This version is compatible with Vue 3. If you are looking for a Vue 2.x compatible version, check out the V1 branch.Copy the code

Use it directly in main.js

import { createApp } from "vue";
import App from "./App.vue";

createApp(App).use(createPinia()).mount("#app");
Copy the code

Create a store folder. For general projects, we can leave modules alone, but as a rule, I think it makes code easier to read

Such as:

Create module app.js code:

import { defineStore } from "pinia";
export const useAppStore = defineStore({
  // id is required so that Pinia can connect the store to the devtools
  id: "app",
  state: () => ({
    clientWidth: "",
    clientHeight: ""
  }),
  getters: {
    getClientWidth() {
      return this.clientWidth;
    },
    getClientHeight() {
      return this.clientHeight;
    }
  },
  actions: {
    setClientWidth(payload) {
      try {
        setTimeout(() => {
          this.clientWidth = payload;
        }, 2000);
      } catch (error) {}
    },
    setClientHeight(payload) {
      try {
        setTimeout(() => {
          this.clientHeight = payload;
        }, 2000);
      } catch (error) {}
    }
  }
});
Copy the code

Use is actually very simple, as long as the corresponding component in the corresponding module

Such as:

<template> {{ width }} </template> <script> import { ref, reactive, onMounted,computed } from "vue"; import { useAppStore } from "@/store/modules/app"; export default { name: "App", setup() { const appStore = useAppStore(); const width = computed(() => { return appStore.clientWidth; }); onMounted(() => { appStore.setClientWidth(200); }); return { width, }; }}; </script> <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>Copy the code

Pinia can also intuitively use the methods of other modules in the current module

Such as:

import { defineStore } from "pinia"; import { useOtherStore } from "@/store/modules/other.js"; export const useAppStore = defineStore({ // id is required so that Pinia can connect the store to the devtools id: "App ", //state must be a function that returns an object state: () => ({clientWidth: "", clientHeight: ""}), getters: { getClientWidth() { return this.clientWidth; }, getClientHeight() { return this.clientHeight; }, // show a series of events with otherStore otherStoreCount(state) {// here are other stores, call fetch Store, as in setup const otherStore = useOtherStore(); return otherStore.count; }, }, actions: { setClientWidth(payload) { try { setTimeout(() => { this.clientWidth = payload; }, 2000); } catch (error) {} }, setClientHeight(payload) { try { setTimeout(() => { this.clientHeight = payload; }, 2000); } catch (error) {}}, // To tell someone a story with action setOtherStoreCount(state) {// Here are some other stores, call get Store, As in setup const otherStore = useOtherStore(); otherStore.setMethod() }, } });Copy the code

Three, several methods of changing state by Actions in Pinia

After introducing the corresponding module into the component, we can see the following:

<template> {{ width }} </template> <script> import { ref, reactive, onMounted,computed } from "vue"; import { useAppStore } from "@/store/modules/app"; export default { name: "App", setup() { const appStore = useAppStore(); const width = computed(() => { return appStore.clientWidth; }); onMounted(() => { appStore.setClientWidth(200); }); // State const changeAppstoreStateClick = () => {// State const changeAppstoreStateClick = () => { $patch({clientWidth: appStore. ClientWidth + 400,}) $patch({clientWidth: appStore. ClientWidth + 400,}); $appStore.$patch((state) => {state. ClientWidth += 400; }); }; return { width, changeAppstoreStateClick }; }}; </script> <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>Copy the code