preface

Pinia. Js is the next generation of state manager, developed by members of vuue. Js team.

Pinia.js has the following features:

  • Full typescript support;
  • Lightweight enough, compressed volume is only 1.6KB;
  • Remove mutations, only state, getters, actions (one of my favorite features);
  • Actions support synchronous and asynchronous;
  • There is no module nesting, only the concept of stores, stores can be used freely, better code segmentation;
  • There is no need to manually add stores, stores are automatically added once created;

The installation

npm install pinia --save
Copy the code

Create the Store

Create a SRC /store directory and create index.ts under it to export store

// src/store/index.ts

import { createPinia } from 'pinia'

const store = createPinia()

export default store
Copy the code

Introduced and used in main.ts.

// src/main.ts

import { createApp } from 'vue'
import App from './App.vue'
import store from './store'

const app = createApp(App)
app.use(store)
Copy the code

State

Define the State

Create a user.ts under SRC /store

//src/store/user.ts

import { defineStore } from 'pinia'

export const useUserStore = defineStore({
  id: 'user'.state: () = > {
    return {
      name: 'Joe'}}})Copy the code

Access to the state

<template>
  <div>{{ userStore.name }}</div>
</template>

<script lang="ts" setup>
import { useUserStore } from '@/store/user'

const userStore = useUserStore()
</script>
Copy the code

It can also be combined with computed acquisition.

const name = computed(() = > userStore.name)
Copy the code

State can also use deconstruction, but using deconstruction makes it unresponsive, so Pinia’s storeToRefs can be used instead.

import { storeToRefs } from 'pinia'
const { name } = storeToRefs(userStore)
Copy the code

Change the state

You can modify state directly as follows

userStore.name = 'bill'
Copy the code

However, this is not recommended. It is recommended to change the state through actions, which can be accessed directly through this.

export const useUserStore = defineStore({
  id: 'user'.state: () = > {
    return {
      name: 'Joe'}},actions() {
    updateName(name) {
      this.name = name
    }
  }
})
Copy the code
<script lang="ts" setup>
import { useUserStore } from '@/store/user'

const userStore = useUserStore()
userStore.updateName('bill')
</script>
Copy the code

Getters

export const useUserStore = defineStore({
 id: 'user'.state: () = > {
   return {
     name: 'Joe'}},getters: {
   fullName: (state) = > {
     return state.name + 'company'}}})Copy the code
userStore.fullName / / zhang sanfeng
Copy the code

Actions

Asynchronous action

Actions can support async/await syntax just like writing a simple function, allowing you to happily deal with asynchronous processing scenarios.

export const useUserStore = defineStore({
  id: 'user'.actions() {
    async login(account, pwd) {
      const { data } = await api.login(account, pwd)
      return data
    }
  }
})
Copy the code

Actions call each other

Calls between actions can be accessed using this.

 export const useUserStore = defineStore({
  id: 'user'.actions() {
    async login(account, pwd) {
      const { data } = await api.login(account, pwd)
      this.setData(data) // Call another action method
      return data
    },
    setData(data) {
      console.log(data)
    }
  }
})
Copy the code

It is also easy to call an action from another store. After importing the corresponding store, you can call its action method.

// src/store/user.ts

import { useAppStore } from './app'
export const useUserStore = defineStore({
  id: 'user'.actions() {
    async login(account, pwd) {
      const { data } = await api.login(account, pwd)
      const appStore = useAppStore()
      appStore.setData(data) // Call the app Store action method
      return data
    }
  }
})
Copy the code
// src/store/app.ts

export const useAppStore = defineStore({
  id: 'app'.actions() {
    setData(data) {
      console.log(data)
    }
  }
})
Copy the code

Data persistence

The plug-in pinia-plugin-persist assists in data persistence.

The installation

npm i pinia-plugin-persist --save
Copy the code

use

// src/store/index.ts

import { createPinia } from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist'

const store = createPinia()
store.use(piniaPluginPersist)

export default store
Copy the code

Then enable Persist in the corresponding store.

export const useUserStore = defineStore({
  id: 'user'.state: () = > {
    return {
      name: 'Joe'}},// Enable data caching
  persist: {
    enabled: true}})Copy the code

Data is stored in sessionStorage by default, and the store ID is used as the key.

The custom key

You can also customize key values in strategies and change the storage location from sessionStorage to localStorage.

persist: {
  enabled: true.strategies: [{key: 'my_user'.storage: localStorage,}}]Copy the code

Persist part state

By default, all states are cached, so you can specify fields to persist through Paths and not others.

state: () = > {
  return {
    name: 'Joe'.age: 18.gender: 'male'}},persist: {
  enabled: true.strategies: [{storage: localStorage.paths: ['name'.'age']]}}Copy the code

Above we only persist name and age and change them to localStorage, while gender is not persisted. If its state is changed, it will be lost when the page is refreshed and returned to its original state, while name and age are not.

Thank you

This is the end of the sharing, thank you for reading this article, if you have any help, don’t forget to move to give a thumbs up ❤️.

If there are any mistakes or deficiencies in this article, welcome to the comment section correction!