Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use pinia in Vue

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of how to use pinia in Vue, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this Vue article on how to use pinia. Let's take a look at it.

What is Pinia?

Pinia was originally an experiment to redesign the Vue Store look and feel using Composition API around November 2019. Since then, the initial principles have remained the same, but Pinia applies to Vue 2 and Vue 3, and you don't need to use a combined API. Except for installation and SSR, the API is the same for both, and these documents are for Vue 3 and, if necessary, provide comments about Vue 2 so that Vue 2 and Vue 3 users can read them!

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 rendered on the server side, 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 tool support

Track the schedule of movements and sudden changes

Stores appear in the components that use them

Time travel and easier debugging

Hot module replacement

Modify your store without reloading the page

Maintain any existing state during development

Plug-ins: using plug-ins to extend Pinia functionality

Provide appropriate TypeScript support or auto-completion for JS users

Server-side rendering support

Basic example

This is what pinia looks like in terms of API (be sure to check out how to get started for full instructions). You first create a store:

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

Then use it in the component:

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 not familiar with setup () Composition API, don't worry, Pinia also supports a similar set of map helpers, such as Vuex. You define storage in 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 the core concepts.

Why choose Pinia?

Pinia (pronounced / pi "nj" /, such as "peenya" in English) is the word closest to pi ñ a (pineapple in Spanish), which is a valid package name. A pineapple is actually a single group of flowers that combine to form multiple fruits. Like stores, each is born independently, but in the end it is all connected. It is also a delicious tropical fruit, native to South America.

A more realistic example

This is a more complete example of API, and you will use types in Pinia, even in JavaScript. For some, this may be enough to start without further reading, but we still recommend that you look at the rest of the document, or even skip the example and return after reading all the core concepts.

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 Comparison between return a promise or not addTodo (text) {/ / you can directly mutate the state this.todos.push ({text, id: this.nextId++, isFinished: false})},},}) and Vuex

Pinia tries to get as close as possible to the idea of Vuex. It was designed to test Vuex's proposal for the next iteration and was successful because we currently have an open RFC for Vuex 5 whose API is very similar to the API used by Pinia. Please note that I (Eduardo), the author of Pinia, is a member of the core team of Vue.js and is actively involved in the design of API such as Router and Vuex. My personal intention for this project is to redesign the experience of using global stores while maintaining Vue's approachable philosophy. I keep Pinia's API as close as Vuex because it continues to move forward to make it easier for people to migrate to Vuex and even integrate the two projects in the future (under Vuex).

RFC

Although Vuex collects as much feedback as possible from the community through RFC, Pinia does not. I test ideas based on my experience developing applications, reading other people's code, working for customers who use Pinia, and answering questions on Discord. This enables me to provide an effective solution for a variety of situations and application sizes. I often release 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

Pinia API is very different from Vuex ≤ 4, namely:

The mutation no longer exists. They are often considered to be very lengthy. They initially brought devtools integration, but this is no longer a problem.

There is no need to create custom complex wrappers to support TypeScript, everything is typed, and API is designed to take advantage of TS type inference as much as possible.

No longer need to inject magic strings, import functions, call them, enjoy the autocomplete function!

There is no need to add stores dynamically, they are all dynamic by default, and you won't even notice. Please note that you can still register manually using the store at any time, but because it is automatic, you don't have to worry.

There is no longer a nested structure of modules. You can still implicitly nest stores by importing and using stores in another store, but Pinia provides a flat structure through design while still supporting cross-assembly between stores. You can even have a circular dependency on store.

A module without a namespace. Given the flat structure of the store, the "namespace" store is inherent in the way it is defined, and you can say that all stores are namespaced.

This is the end of the article on "how to use pinia in Vue". Thank you for reading! I believe you all have a certain understanding of "how to use pinia in Vue". If you want to learn more, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report