[Use and Explanation of vue3 Pinia] The New Generation Store Application of vue3

This article is intended to quickly help you get started with the basic and core parts of Pinia. For a complete understanding, see the official website or follow-up articles (rewrite when available), and Pinia can also be used in SSR. Also: This Chinese name can be called pineapple. It originated from the Spanish language PIA and was translated into pineapple in Chinese.

Pinia Summary:

Pinia began by exploring what Vuex's next iteration would look like, incorporating many ideas from the Vuex 5 core team discussion.
Finally, we realized that Pinia had achieved most of the functionality we wanted in Vuex 5 and decided to make Pinia a new recommendation.

Pinia offers a simpler, less rigid API than Vuex, and a Composition-API-style API.
Better type inference support when used with TypeScript.

What is Pinia Store?

Store s, such as Pinia, exist independently and hold state and business logic without binding to the component tree.
In other words, it is the master of the global state.
It's kind of like a component, it's always there, everybody can read and write.
It contains three concepts, state, getters, and actions, which can be understood as equivalent to data, computed, and methods in components.

When should I use Store?

Storage should contain data that can be accessed throughout the application.
This includes data used in many places, such as user information displayed in the navigation bar, and data that needs to be saved through the page, such as very complex multi-step forms.
On the other hand, you should avoid storing internal data in a component in Store, such as the visibility of elements within a component template.
Not all applications need access to the global state, but Pinia will make your development easier if you need one.

Pinia's main Api

  * createPinia
    - Plugins
* defineStore >> Declare a Store
* storeToRefs >> see `4. ` Use cases
* mapState >>Used in computed for vue component options
* Alias of mapGetters >> mapState, use mapState instead
* mapActions >>Used in methods of options of vue components
* getActivePinia >>Get the currently active pinia instance, if any.
- Store's core configuration:
  + State
  + Getters
  + Actions

How vite + vue3 is used:

1. npm install pinia

2. Create a pinia and pass it to the vue application instance:

  import { createPinia } from 'pinia'
  app.use(createPinia())

3. Define Store

Before delving into the core concepts, we need to know that Pinia is defined using defineStore(), and that it requires a unique name to be passed as the first parameter:
Name (also known as id) is required, and Pinia uses the name parameter to connect the Store to devtools.
Naming the returned function `use...'is a cross-component convention that normalizes its use.

  • defineStore(name,options)
    • name: required, type `string`
    • options:{}
import { defineStore } from 'pinia'
// useStore can be anything like useUser, useCart
// The first parameter is the unique id of the Store in the application
export const useStore = defineStore('main', {
  // state: () => ({ count: 0 }),
  state:()=>{
    return {
      // All these properties will automatically infer their data type
      items: [],
      counter: 0,
      name: 'Eduardo',
      isAdmin: true,
    }
  },
  getters: {
    doubleCount: (state) => state.counter * 2,
  },
  actions: {
    increment(num,test1,test2) {
      console.log(num,test1,test2)
      this.counter++
    },
    randomizeCounter() {
      this.counter = Math.round(100 * Math.random())
    },
  }
})



4. Use Store

We declare the store because it will not be created until `setup()` is called internally `useStore()':

Also, don't spit in a slot that's not <script setup>, do anything for example, and don't even copy [laugh and cry]

<template>
  <p>Double count is {{ store.doubleCount }}</p>
</template>
<script>
import { useStore,mapState } from '@/stores/counter'
export default {
  setup() {
    const store = useStore()
    store.counter++
    store.$patch({ // In addition to using the store directly. Counter++ alters the store in addition to calling the $patch method. state allows you to apply multiple changes to some objects simultaneously:
      counter: store.counter + 1,
      name: 'Abalam',
    })

    store.$patch((state) => { // The $patch method also accepts a function to group such mutations that are difficult to apply to patch objects:
      state.items.push({ name: 'shoes', quantity: 1 })
      state.isAdmin = false
    })

    store.increment(9,'Test Multi-parameter 1','Test 2') // Call actions and pass in parameters
    store.randomizeCounter() // Call actions
    return {
      // You can return the entire store instance to use it in the template
      store,
    }
  },
  computed: { 
    storeCounter() {
      return this.store.counter * 3
    },
    // ... mapState(useCounterStore, ['counter'])//Use this only when there is no setup
  },
}
</script>


Define Multiple Store s

You can define as many Stores as you want, and each Store should be defined in a different file to take full advantage of pinia (for example, automatically allowing your package to do code splitting and TypeScript inference).

Once the Store is instantiated, you can directly access any properties defined in state, getter, and actions on the store.

Matters needing attention!

// Note that store is an object wrapped in a reactive, meaning you don't need to write after getters. value;
// So just like props in setup, you can't deconstruct their objects!
export default defineComponent({
  setup(props) {
    const store = useStore()
    // ❌  This does not work because it would break the response >> This won't work because it breaks reactivity
    // This is the same as deconstructing from `props'>> it's the same as destructuring from `props`
    const { name, doubleCount } = store
    console.log(name) // "eduardo"
    console.log(doubleCount) // 2
    return {
      // Always "eduardo" > will always be "eduardo"
      name,
      // will always be 2
      doubleCount,
      // This is normal responsive data > this one will be reactive
      doubleValue: computed(() => store.doubleCount),
      }
  },
})


In order to extract attributes from a Store while maintaining the responsiveness of its data, you need to use storeToRefs(). It will create refs for any responsive attributes.
This is useful when you only use the state in the store but do not call any action s:

import { storeToRefs } from 'pinia'
export default defineComponent({
  setup() {
    const store = useStore()
    // `name` and `doubleCount` are responsive refs data
    // This will also create references to the properties added by the plug-in
    // However, any action s and attributes that are not reactive (non-ref/reactive) are skipped
    const { name, doubleCount } = storeToRefs(store)

    return {
      name,
      doubleCount
    }
  },
})

Keywords: Javascript Front-end TypeScript Vue

Added by mahendrakalkura on Wed, 23 Feb 2022 19:28:46 +0200