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, a new member of Vue ecology

2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Editor to share with you how to use Pinia, a new member of Vue ecology, I believe most people do not know much about it, so share this article for your reference. I hope you will learn a lot after reading this article. Let's learn about it together.

Pinia is the state management solution for Vue applications and is developed by members of the Vuex core team. It feels more like a regular old javascript import module that implements a lot of Vuex5 proposals.

Pinia supports both Vue2 and Vue3, but the following examples show that the version that uses Vue3,Pinia is Pinia@2.0.9.

The version of Pinia used by Vue2 and Vue3 is slightly different, so check the official Pinia documentation for more information.

Installation and configuration

You can install Pinia using npm or yarn

Yarn add pinia@next# or use npmnpm install pinia@next

After installation, find the file main.js of the Vue application (the project initialized by vue-cli is generally named main.js). Import createPinia from Pinia's npm package and use Vue's use method as a plug-in

/ / main.jsimport {createApp} from 'vue'import App from'. / App.vue'import router from'. / router'import {createPinia} from 'pinia'createApp (App) .use (router) .use (createPinia ()) .mount (' # app')

Next, let's create a store

Store core

The Store of Pinia is different from the Store of Vuex. When using Vuex, the entire application has only one primary Store (although you can split it into different modules, it is still a main storage outlet). However, today's protagonist Pinia is a modular design that works out of the box. Instead of needing a major Store, you can create a different Store. For example, we can create a login user Store.

/ / store/loggedInUser.jsimport {defineStore} from 'pinia'export const useLoggedInUserStore = defineStore ({/ / id is required and unique among all Store, because Pinia will display it in devtools id:' loggedInUser', state () {return {name: 'too cold', age: 18, email: 'fake@email.com'}, getters: {}, actions: {}})

Above we have created a login user Store, which we can refer to directly in the component and then call useLoggedInUserStore in the setup function

PiniaApage name: {{user.name}} Age: {{user.age}} import {useLoggedInUserStore} from'@ / store/loggedInUser.js'export default {name: 'PiniaDemoPage1', setup () {const user = useLoggedInUserStore () return {user}

This is very different from Vuex. The Store of Vuex is automatically mounted to the instance of the current Vue and can be called through this.$store. However, the Pania approach also gives developers a better idea of where Store comes from, because it is a standard Javascript module import, and you can see from which file it was imported.

If you don't use Composition API, you can still use Pinia with some helper functions. I'll talk about it in detail below.

State

We set the state property in Store to a function that returns an object with different state values. This is very similar to the way we define data in a component. In fact, the only difference is the attribute name: status and data

Import {defineStore} from 'pinia'export const useLoggedInUserStore = defineStore ({/ / id is required and unique among all Store, because Pinia will display it in devtools id:' return {name: 'too cold', age: 18, email: 'fake@email.com'}}, getters: {}, actions: {}})

Now, in order to access the state of the loginUserStore from the component, we only need to reference the Store we need, which is very elegant. There is no need to find the Store we need from nested objects like Vuex does.

PiniaApage name: {{user.name}} Age: {{user.age}} import {useLoggedInUserStore} from'@ / store/loggedInUser.js'export default {name: 'PiniaDemoPage1', setup () {/ / get const user = useLoggedInUserStore () return {user}} without thinking about the previous user.state.name.

Warning, do not structure user, because you will lose the responsiveness. The following way is wrong.

❌ const {name, email} = useLoggedInUserStore ()

If you are not using the Composition API way, but the Option API way. You can get State data through the mapState function of Pinia. The mapState function of Pinia and the mapState of Vuex have the same name, but they are used in a completely different way.

The first argument to Pinia's mapState function must be the previously created Store, and the second argument is the property value of state in Store. Look at the code.

/ / PageComponent.vue Hello, I'm {{name}}, I'm from Earth contact email: {{email}} import {mapState} from 'pinia'export default {computed: {... mapState (useLoggedInUserStore, [' name','email'])}}

Summary:

Define the state of a Pinia in the same way as the data of a component

We need to manually import the Store modules we need between components, which has the advantage of knowing clearly the source of the data and a more standard Javascript.

Getters

The role of getters in Pinia is the same as that of getters in Vuex, both as computed of components.

There are two ways to create a getters, one is to use the this keyword, and the other is to look at the code through state

/ / store/usePostsStore.jsimport {defineStore} from 'pinia'export const usePostsStore = defineStore ({id:' PostsStore', state: () = > ({posts: ['post 1,' post 2, 'post 3,' post 4]}), getters: {/ / traditional function postsCount: function () {return this.posts.length} / / traditional function abbreviation postsCount2 () {return this.posts.length}, / / Arrow function postsCount3: (state) = > state.posts.length, / / Arrow function + this cannot be used In this way, this points to incorrect / / postsCount: () = > this.posts.length}})

Next, let's take a look at how the created getters is used in Composition API-style components, which is actually the same as state. Look at the code.

Total PiniaBpage: {{postsStore.postsCount}} import {usePostsStore} from'@ / store/usePostsStore.js'export default {name: 'PiniaBpage', setup () {const postsStore = usePostsStore () return {postsStore}

If it is a component of Option API, it cannot be obtained through the mapGetters helper function as Vuex does. Because there is no mapGetters helper function in Pinia, the consumption of getters in Pinia still depends on the mapState helper function.

Total: {{postsCount}} import {mapState} from 'pinia'import {usePostsStore} from "@ / store/PostsStore"; export default {computed: {... mapState (usePostsStore, [' postsCount'])}}; Actions

Unlike Vuex,Pinia, Pinia provides a single way to change the value of state. There is no mutations in Pinia, only action mode. Let's first take a look at how to use Pinia's action. Upper code

Find the corresponding state modification directly through this

Through. $patch function method

Through the. $patch object method

Import {defineStore} from 'pinia'export const usePostsStore = defineStore ({id:' PostsStore', state: () = > ({posts: ['post 1,' post 2, 'post 3,' post 4'], user: {postsCount: 2}, age:18, errors: []}), getters: {postsCount: function () {return this.posts.length} PostsCount2 () {return this.posts.length}, / / arrow function postsCount3: (state) = > state.posts.length}, actions: {insertPost () {/ / method 1: find the corresponding state modification this.posts.push (`post_$ {Date.now ()} `) this.user.postsCount++} directly through this RemovePost () {/ / Mode 2: through. $patch function method this.$patch ((state) = > {state.posts.shift () state.user.postsCount++}) / / through. $patch object method this.$patch ({age:30}) })

The above shows three State ways to change Pinia.

If it is the way Composition API is used,

Total number of PiniaBpage: {{postsStore.postsCount}} {{item}} add deletion add to the front import {usePostsStore} from'@ / store/usePostsStore.js' export default {name: 'PiniaBpage' Setup () {const postsStore = usePostsStore () / add const handleAdd = () = > {postsStore.insertPost ()} / delete const handleRemove = () = > {postsStore.removePost ()} / / add to the front You can also modify it here via $patch, or you can modify const handleBeforeAdd= () > {postsStore.$patch ((state) = > {state.posts.shift () state.user.postsCount++})} return {postsStore, handleAdd, handleRemove, handleBeforeAdd}}

If you are using Options API, you need to use the auxiliary function mapActions.

/ / PostEditorComponent.vue saves import {mapActions} from 'pinia'import {usePostsStore} from' @ / store/PostsStore';export default {data () {return {post:''}}, methods: {... mapActions (usePostsStore, ['insertPost'])}}

In fact, the action of Pinia is very flexible.

Can be called in a component or other actions

Can be called in the actions of other Store

Import {useAuthStore} from'. / auth-store'export const useSettingsStore = defineStore ('settings', {state: () = > ({/ /...}), actions: {async fetchUserPreferences (preferences) {const auth = useAuthStore () if (auth.isAuthenticated) {this.preferences = await fetchPreferences ()} else {throw new Error (' User must be authenticated')},},})

Support for synchronous and asynchronous

Can support flexible parameters

.

Vue Devtools

In Vue 2, Pania allows you to view the status and even the time trajectory in the Vuex tab. The label for time tracks is hardly as good as it is when used in Vuex.

As for Vue 3 Magi Pania, it only supports checking status in devtools, but does not support time track function. However, this is actually more than Vuex provides for Vue 3, because it is not supported at all in the latest development tools.

Last

A quick review of the most significant features of Pinia to help you quickly understand Pinia and apply it to your project

Maintained by Vue.js core team members

It feels more like a regular old javascript import module, taking actions as method calls, accessing status directly on the store, and so on.

No longer mutations

Integrate with Vue Devtools

Conclusion

Although Pinia is a new member of Vue ecology, Pinia has proved to be the most promising state management solution with intuitive API, modularization and clear import sources.

The above is all the contents of the article "how to use Pinia, a new member of Vue Ecology". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, 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