Hello everyone, I haven’t updated my article for a while. What have I been doing recently? Recently, I suddenly decided to renovate a blog project in my university, and completed the full stack development by using nuxt+egg.js. Therefore, I have been busy designing this project and it will be almost completed. When it comes to open source, please click “star” if you like

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', // id mandatory and requires a unique state: () => {return {name: 'small fluorescence'}}})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 = 'li si'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: 'defineStore'}}, actions: { updateName(name) { this.name = name } } })Copy the code
<script lang="ts" setup> import { useUserStore } from '@/store/user' const userStore = useUserStore() Userstore. updateName(' updateName ') </script> Copy codeCopy the code

Getters

Export const useUserStore = defineStore({id: 'user', state: () => {return {name: 'user'}}, getters: {fullName: (state) => {return state.name + 'feng'}}})Copy the code
Userstore. fullName // XiaoyingfengCopy 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 access its internal methods.

// 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 action method in appStore 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 codeCopy the code

Then enable Persist in the corresponding store.

Export const useUserStore = defineStore({id: 'user', state: () => {return {name: 'user'}}, // enable data cache 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: 'zhang SAN ', 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.

The last

The above is about the usage of Pinia. Js some introduction, Pinia. Js content is far more than these, more content and use to be explored by yourself. Pinia document

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!