Table of Contents
What is Pinia?
Why use Pinia?
Basic example
Why choosePinia
RFC
Comparison with Vuex 3.x/4.x
Home Web Front-end Vue.js What is pinia? How to use it in Vue?

What is pinia? How to use it in Vue?

Feb 09, 2022 am 10:58 AM
pinia vue

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++
    },
  },
})
Copy after login

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()
  },
}
Copy after login

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 }
})
Copy after login

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']),
  },
}
Copy after login

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 })
    },
  },
})
Copy after login
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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

How to jump to the div of vue How to jump to the div of vue Apr 08, 2025 am 09:18 AM

There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.

See all articles