In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article is about how to use Vue's new state management Pinia. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
As an old Vue state management library, Vuex is familiar to everyone.
Pinia is a new state management library developed by Vue.js team members specifically for Vue, and has been incorporated into the official github
Why develop another Pinia when you have Vuex?
Let's take a picture and take a look at the proposal for Vuex5 at that time, that is, what the next generation of Vuex5 should look like. [related recommendation: vuejs video tutorial]
Pinia is completely in line with the function points mentioned in his Vuex5 proposal at that time, so it is not too much to say that Pinia is Vuex5, because its author is an official developer and has been taken over by the authorities, but at present, Vuex and Pinia are still two independent warehouses, which may be merged or developed independently in the future, but the official recommendation is Pinia.
Because using Vuex in Vue3 requires Vuex4 and can only be used as a transitional choice, there are great defects, so after the birth of Componsition API, a brand-new state management Pinia was designed.
Pinia and Vuex
Vuex: State, Gettes, Mutations (synchronous), Actions (asynchronous)
Pinia: State, Gettes, Actions (both synchronous and asynchronous are supported)
The latest version of Vuex is 4.x.
Vuex4 is used for Vue3
Vuex3 is used for Vue2
The latest version of Pinia is 2.x.
Both Vue2 and Vue3 are supported
At present, Pinia is much better than Vuex, and it solves many problems of Vuex, so the author very much recommends using Pinia directly, especially for TypeScript projects.
Core features of Pinia
Pinia has no Mutations
Actions supports synchronous and asynchronous
Nested structure without modules
Pinia provides a flat structure through design, which means that each store is independent of each other and belongs to no one, that is, flattened, better code segmentation and no namespaces. Of course, you can also implicitly nest store by importing another module in one module, and you can even have circular dependencies of store.
Better TypeScript support
There is no need to create custom complex wrappers to support all TypeScript content typing, and API is designed to use TS type inference as much as possible
There is no need to inject, import functions, call them, and enjoy automatic completion, which makes it more convenient for us to develop
There is no need to add store manually, its modules are automatically registered when they are created by default
Both Vue2 and Vue3 support
With the exception of initializing the installation and SSR configuration, the API used by both is the same
Support for Vue DevTools
Track the timeline of actions and mutations
The module itself can be observed in the components that use the module
Support for time-travel makes debugging easier
In Vue2, Pinia uses all interfaces of Vuex, so they cannot be used together.
But the debug tool support for Vue3 is not perfect, for example, there is no time-travel function.
Module hot update
You can modify the module without reloading the page
Any existing state will be maintained during a hot update
Support for using plug-ins to extend Pinia functionality
Support server-side rendering
Pinia usage
Take Vue3 + TypeScript as an example
Installation
Npm install pinia
Main.ts initialization configuration
Import {createPinia} from 'pinia'createApp (App) .use (createPinia ()) .mount (' # app')
To create a user.ts under the store directory as an example, we first define and export a module called user
Import {defineStore} from 'pinia'export const userStore = defineStore (' user', {state: () = > {return {count: 1, arr: []}}, getters: {...}, actions: {...}})
DefineStore receives two parameters
The first parameter is the name of the module, which must be unique. Multiple modules cannot have the same name. Pinia will mount all modules to the root container.
The second parameter is an object with options similar to Vuex.
The state is used to store the global state, and it must be an arrow function. In order to avoid data state contamination caused by cross requests when rendering on the server, it can only be a function, while the arrow function must be used for better TS type derivation.
Getters is used to encapsulate computing properties, and it has the function of caching.
Actions is used to encapsulate business logic and modify state.
Visit state
For example, we need to access the attribute count in state in the page.
Because defineStore returns a function, you need to call the data object first, and then you can use it directly in the template.
{{user_store.count}} import {userStore} from'.. / store'const user_store = userStore () / deconstruct / / const {count} = userStore ()
For example, if you want to deconstruct a comment and use it, there is no problem at all. Just note that the data obtained in this way is not responsive. If you want to deconstruct and remain responsive, you need to use a method called storeToRefs (). The example is as follows
{{count}} import {storeToRefs} from 'pinia'import {userStore} from'.. / store'const {count} = storeToRefs (userStore)
The reason is that Pinia actually does reactive processing of state data, which is the same as Vue3's reactive, and the deconstruction is not responsive, so we need to do ref responsive agent again.
Getters
Like Vuex's getters, this also has caching capabilities. The following is used many times in the page. Getters will be called for the first time, and the cache will be read after the data has not changed.
{{myCount}} {{myCount}} {{myCount}}
Pay attention to the difference between the two methods. It's in the notes.
Getters: {/ / method 1, receive an optional parameter state myCount (state) {console.log ('called') / / page three times, which will only be executed once, and then cache return state.count + 1}, / / method 2, do not pass parameters, use this / / but you must specify the type of function return value Otherwise, the type cannot be deduced from myCount (): number {return this.count + 1}} update and actions
There are four ways to update the data in state. Let's first look at three simple updates, which are all written in the comments.
{{user_store.count}} button import {userStore} from'.. / store'const user_store = userStore () const handleClick = () = > {/ / method 1 user_store.count++ / / method 2. Multiple data needs to be modified. It is recommended to update it in batches with $patch. Pass in an object user_store.$patch ({count: user_store.count1++, / / arr: user_store.arr.push (1) / / error arr: [. User_store.arr, 1] / / Yes, but it is not necessary to deconstruct the entire array) / / use $patch for better performance Because multiple data updates will update view / / method 3 only once, or $patch, pass in the function, and the first argument is state user_store.$patch (state = > {state.count++ state.arr.push (1)})}
The fourth method is that when there is too much logic or a request, we can encapsulate it in the actions in the store/user.ts in the example.
You can pass parameters, or you can get the data in the state directly through this.xx. It should be noted that the actions cannot be defined with the arrow function, otherwise the external this will be bound.
Actions: {changeState (num: number) {/ / cannot use the arrow function this.count + = num}}
Call
Const handleClick = () = > {user_store.changeState (1)} supports VueDevtools
If you open the Vue Devtools of the developer's tool, you will find Pinia, and you can manually modify the data and debug, which is very convenient.
Analog call interface
Example:
Let's first define the sample interface api/user.ts
/ / API data type export interface userListType {id: number name: string age: number} / / data returned by the simulation request API const userList = [{id: 1, name: 'Zhang San', age: 18}, {id: 2, name:'Li Si', age: 19},] / / encapsulates the timer async function wait (delay: number) {return new Promise ((resolve) = > setTimeout (resolve)) that simulates the asynchronous effect Delay)} / / Interface export const getUserList = async () = > {await wait / / delay 100ms to return return userList}
Then encapsulate the calling interface in actions in store/user.ts
Import {defineStore} from 'pinia'import {getUserList, userListType} from'.. / api/user'export const userStore = defineStore ('user', {state: () = > {return {/ / user list list: [] as userListType / / convert type to userListType}}) Actions: {async loadUserList () {const list = await getUserList () this.list = list}})
Call actions in the page to initiate the request
... Import {userStore} from'.. / store'const user_store = userStore () user_store.loadUserList () / / load all data and modify data across modules
You need to modify the state data of another module in the actions of one module.
Example: for example, modify the name of a user in the user module in the chat module
/ / chat.tsimport {defineStore} from 'pinia'import {userStore} from'. / user'export const chatStore = defineStore ('chat', {actions: {someMethod (userItem) {userItem.name =' new name 'const user_store = userStore () user_store.updateUserName (userItem)})
In the user module
/ / user.tsimport {defineStore} from 'pinia'export const userStore = defineStore (' user', {state: () = > {return {list: []}}) Actions: {updateUserName (userItem) {const user = this.list.find (item = > item.id = = userItem.id) if (user) {user.name = userItem.name}) Thank you for reading! This is the end of this article on "how to use Vue's new state management Pinia". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.