Home  >  Article  >  Web Front-end  >  What is pinia? How to use it in Vue?

What is pinia? How to use it in Vue?

青灯夜游
青灯夜游forward
2022-02-09 10:58:2025592browse

What is pinia? Why use Pinia? This article will introduce you to pinia and introduce the basic usage of pinia through examples. I hope it will be helpful to you!

What is pinia? How to use it in Vue?

What is Pinia?

Pinia was originally an experiment around November 2019 to redesign the appearance of the Vue Store using Composition API. From then on, the original principles remain the same, but Pinia works on both Vue 2 and Vue 3 and doesn't require you to use the composition API. Apart from Installing and SSR, the API for both is the same, and the documentation is specific to Vue 3, with providing notes on Vue 2 where necessary for Vue 2 and Vue 3 users can read! [Related recommendations: vue.js video tutorial]

Why use Pinia?

Pinia is a repository for Vue that allows you to share state across components/pages. ç This is true for a single-page application, but if it is server-side rendered, it exposes your application to security vulnerabilities. But even in small single-page applications, you can get a lot of benefits from using Pinia:

  • Development tools support

    • Tracking actions , mutation timelines
    • Stores appear in components that use them
    • Time travel and easier debugging
  • Hot module replacement

    • Modify your store without reloading the page
    • Keep any existing state while developing
  • Plugins: Use plugins to extend Pinia functionality

  • Provide proper TypeScript support for JS users orautocomplete functionality

  • server Side rendering support

Basic example

This is what using pinia looks like API-wise (be sure to check out Getting Started for full instructions). You first create a store:

// stores/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => {
    return { count: 0 }
  },
  // could also be defined as
  // state: () => ({ count: 0 })
  actions: {
    increment() {
      this.count++
    },
  },
})

and then in a component use it:

import { useCounterStore } from '@/stores/counter'

export default {
  setup() {
    const counter = useCounterStore()

    counter.count++
    // with autocompletion ✨
    counter.$patch({ count: counter.count + 1 })
    // or using an action instead
    counter.increment()
  },
}

You can even use a function (similar to a component setup() ) to define a Store for more advanced use cases:

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  function increment() {
    count.value++
  }

  return { count, increment }
})

If you are still unfamiliar with the setup()Composition API, don’t worry, Pinia also supports a similar set of ##Map Assistant, such as Vuex. You define storage the same way, but then use mapStores(), mapState(), or mapActions():

const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    double: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    }
  }
})

const useUserStore = defineStore('user', {
  // ...
})

export default {
  computed: {
    // other computed properties
    // ...
    // gives access to this.counterStore and this.userStore
    ...mapStores(useCounterStore, useUserStore)
    // gives read access to this.count and this.double
    ...mapState(useCounterStore, ['count', 'double']),
  },
  methods: {
    // gives access to this.increment()
    ...mapActions(useCounterStore, ['increment']),
  },
}

you will Find more information about each map assistant in Core Concepts.

Why choosePinia

Pinia (pronounced /piːnjʌ/, as in English “peenya”) is the closest # The word ##piña (pineapple in Spanish), which is a valid package name. A pineapple is actually a group of individual flowers that join together to form multiple fruits. Similar to stores, each is born independently, but ultimately all are connected. It is also a delicious tropical fruit native to South America.

A more realistic example

This is a more complete example of the API that you will use types in Pinia

even in JavaScript. For some, this may be enough to get started without reading further, but we still recommend that you review the rest of the documentation or even skip this example and read all Core Concepts return.

import { defineStore } from 'pinia'

export const todos = defineStore('todos', {
  state: () => ({
    /** @type {{ text: string, id: number, isFinished: boolean }[]} */
    todos: [],
    /** @type {'all' | 'finished' | 'unfinished'} */
    filter: 'all',
    // type will be automatically inferred to number
    nextId: 0,
  }),
  getters: {
    finishedTodos(state) {
      // autocompletion! ✨
      return state.todos.filter((todo) => todo.isFinished)
    },
    unfinishedTodos(state) {
      return state.todos.filter((todo) => !todo.isFinished)
    },
    /**
     * @returns {{ text: string, id: number, isFinished: boolean }[]}
     */
    filteredTodos(state) {
      if (this.filter === 'finished') {
        // call other getters with autocompletion ✨
        return this.finishedTodos
      } else if (this.filter === 'unfinished') {
        return this.unfinishedTodos
      }
      return this.todos
    },
  },
  actions: {
    // any amount of arguments, return a promise or not
    addTodo(text) {
      // you can directly mutate the state
      this.todos.push({ text, id: this.nextId++, isFinished: false })
    },
  },
})

Comparison with Vuex

Pinia tries to be as close to the Vuex philosophy as possible. It was designed to test proposals for the next iteration of Vuex, and was successful as we currently have an open RFC for Vuex 5 with an API very similar to what Pinia uses

. Please note that I (Eduardo), the author of Pinia, am part of the Vue.js core team and actively participated in the design of APIs such as Router and Vuex. My personal intention with this project was to redesign the experience of using a global store while maintaining Vue’s approachable philosophy. I keep Pinia's API as close to Vuex as it continues to move forward to make it easier for people to migrate to Vuex and even merge the two projects (under Vuex) in the future.

RFC

While Vuex collects as much feedback as possible from the community via RFCs, Pinia does not. I test ideas based on my experience developing apps, reading other people's code, working for clients using Pinia, and answering questions on Discord. This allows me to provide an efficient solution that works across a variety of situations and application sizes. I release frequently and keep the library evolving while keeping its core API unchanged.

Comparison with Vuex 3.x/4.x

Vuex 3.x is Vue 2 of Vuex and Vuex 4.x is Vue 3

The Pinia API is significantly different from Vuex ≤4, namely:

  • Mutation no longer exists. They are often considered veryverbose. They originally brought devtools integration, but that's no longer an issue.
  • There is no need to create custom complex wrappers to support TypeScript, everything is typed, and the API is designed in a way to leverage TS type inference whenever possible.
  • No more injecting magic strings, importing functions, calling them, enjoy autocomplete!
  • No need to add stores dynamically, they are all dynamic by default and you won't even notice. Note that you can still sign up manually using the store at any time, but since it's automatic, you don't need to worry.
  • No more nested structures of modules. You can still nest stores implicitly by importing and using a store within another store, but Pinia provides a flat structure by design while still supporting cross-combination between stores. You can even have circular dependencies on the store.
  • Module without namespace. Given the flat architecture of stores, "namespaced" stores are inherent to the way they are defined, and you could say that all stores are namespaced.

For more detailed instructions on how to convert an existing Vuex ≤4 project to use Pinia, see the Migration from Vuex Guide.

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of What is pinia? How to use it in Vue?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete