Pinia Edible Guide - The Basics

foreword

Pinia, pronounced /piːnjʌ/, is derived from the Spanish piña. It means pineapple, which means that it is composed of many small pieces like pineapple. In Pinia, each Store exists independently and performs state management together. Compared with Vuex, Pinia provides a simpler API, fewer specifications, and a Composition-API style API. What's more, working with TypeScript has solid type inference support.

The difference between Pinia and Vuex

  • Actions support synchronous and asynchronous methods to modify the state.
  • Works with TypeScript with solid type inference support.
  • There is no nesting of modules anymore, only the concept of Store, and Stores can call each other.
  • It supports plug-in extension, which is very convenient to realize functions such as local storage.
  • More lightweight, the compressed volume is only about 2kb.
  • mutations no longer exist. Only state, getters, actions.

basic usage

Install

npm install pinia

Introduced in main.tspinia

// src/main.ts
import {
    
     createPinia } from 'pinia'

const pinia = createPinia()
app.use(pinia)

Define a Store

src/storesCreate a file under the directory setting.js, use defineStore()to define one Store. defineStore()The first parameter is the Id and the second parameter is an options object:

// src/stores/setting.ts
import {
    
     defineStore } from 'pinia'

export const useSettingStore = defineStore('setting', {
    
    
  state: () => ({
    
     count: 0 }),
  getters: {
    
    
    doubleCount: (state) => state.count * 2
  },
  actions: {
    
    
    increment() {
    
    
      this.count++
    }
  }
})

We can also use a more advanced usage, passing a function as the second parameter to define the Store:

我们也可以使用更高级的方法,第二个参数传入一个函数来定义 Store :
// src/stores/setting.ts
import {
    
     ref, computed } from 'vue'
import {
    
     defineStore } from 'pinia'

export const useSettingStore = defineStore('setting', () => {
    
    
  const count = ref(0)
  const doubleCount = computed(() => count.value * 2)
  function increment() {
    
    
    count.value++
  }

  return {
    
     count, doubleCount, increment }
})

used in the component

Import the function just defined in the component and execute it to get the store.

<script setup>
import {
    
     useSettingStore } from '@/stores/setting'

const settingStore = useSettingStore()
// 以下三种方式都会被 devtools 跟踪
settingStore.count++
settingStore.$patch({
    
     count: counterStore.count + 1 })
settingStore.increment()
</script>

<template>
  <div>{
    
    {
    
     settingStore.count }}</div>
  <div>{
    
    {
    
     settingStore.doubleCount }}</div>
</template>

This is the basic usage of pinia. The next Pinia Edible Guide - Advanced will introduce the function of each option and how to use the plugin.

Guess you like

Origin blog.csdn.net/qq_44880095/article/details/128555066