In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces "how to use Pinia of Vue3 state management". In daily operation, I believe that many people have doubts about how to use Pinia of Vue3 state management. The editor has consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "how to use Pinia of Vue3 state management". Next, please follow the editor to study!
The New Development Direction of Vue3 (from Youda Zhihu)
Vue 3 will be the new default version on February 7, 2022
Extremely Fast Construction tool chain based on Vite
Bring the development experience of more silky combinatorial API syntax
Single file component TypeScript IDE support provided by Volar
Command line type checking and generation for single file components provided by vue-tsc
More concise state management provided by Pinia
The new developer tools extension also supports Vue 2/Vue 3 and provides a plug-in system to allow community libraries to extend the developer tools panel on their own.
1. Introduction to Pinia and basic 1.1 Pinia
Official address: https://pinia.vuejs.org/
Pinia is the upgraded version of Vuex4, or Vuex5.
Pinia greatly simplifies the use of Vuex and is a new state management tool for Vue3.
Pinia has better support for ts, better performance, smaller size, no mutations, and can be used for Vue2 and Vue3
Pinia supports Vue Devtools, module hot updates, and server rendering
1.2 Pinia Foundation
Comparison between Vuex and Pinia
Core parts of Vuex: State, Getters, Mutations (synchronous) and Actions (asynchronous)
Core parts of Pinia: State, Getters and Actions (both synchronous and asynchronous are supported)
The function of each part of Pinia
State: similar to data in a component, used to store global state
Getters: similar to computed in components, it encapsulates derived data according to existing State, and also has caching features.
Actions: similar to methods in components, it is used to encapsulate business logic and can be synchronous and asynchronous.
Pinia official sample JS version
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 stat 00e this.todos.push ({text, id: this.nextId++, isFinished: false})},},}) II. The basic usage process of Pinia in Vue3-Vite
① creates a vue vite project
PS C:\ Users\ FORGET\ Desktop\ vue-pinia-demo > npm init vite@latestNeed to install the following packages: create-vite@latestOk to proceed? Y √ Project name:... Pinia-demo √ Select a framework: »vue √ Select a variant: »vue-tsScaffolding project in C:\ Users\ FORGET\ Desktop\ vue-pinia-demo\ pinia-demo...Done. Now run: cd pinia-demo npm install npm run devPS C:\ Users\ FORGET\ Desktop\ vue-pinia-demo > cd.\ pinia-demo\ PS C:\ Users\ FORGET\ Desktop\ vue-pinia-demo\ pinia-demo > npm install
② installs pinia,-S to save it to package.json so that Git can manage it for others to use.
PS C:\ Users\ FORGET\ Desktop\ vue-pinia-demo\ pinia-demo > npm install pinia- S
# dependencies: {"pinia": "^ 2.0.9", "vue": "^ 3.2.25"} in package.json file
③ creates a pinia instance and mounts it to vue
/ / main.ts file import {createApp} from 'vue'import App from'. / App.vue'import {createPinia} from 'pinia'// create Pinia instance const pinia = createPinia () / / create Vue instance const app = createApp (App) / / Mount to Vue root instance app.use (pinia) app.mount (' # app')
④ creates a store folder under the src file and adds index.ts
/ / store/index.tsimport {defineStore} from 'pinia'// 1. Define the container and export the container / / parameter 1: the ID of the container must be unique. After that, Pinia mounts all containers to the root container / / parameter 2: some option objects, that is, state, getter, and action// return values: a function is called to get the container instance export const useMainStore = defineStore ('main', {/ / similar to data in the Vue2 component, which is used to store global state data But there are two requirements / / 1. It must be a function to avoid data state contamination caused by cross requests when rendering on the server / / 2. It must be an arrow function for better TS type derivation state: () = > {return {info: "pinia can be used"}}, getters: {}, actions: {}}) / / 2. Use state// 3. 0 in the container. Modify state / / 4 through getter. Use action synchronous and asynchronous requests in the container
⑤ is used in components
{{mainStore.info}} import {useMainStore} from ".. / store"; const mainStore = useMainStore (); deconstruction access to data in 2.2 state
State management
/ / store/index.tsstate: () = > {return {info: "pinia can be used", count:10}}
In the component
{{mainStore.count}} {{mainStore.info}} {{count}} {{info}}
Modify data
Import {toRefs} from 'vue'import {storeToRefs} from' pinia'import {useMainStore} from ".. / store"; const mainStore = useMainStore (); / / deconstruct the data, but the data obtained is not responsive, only one-time / equivalent to just... mainStore, only reactive processing, not toRefs// const {count, info} = useMainStore (); / / solution: / / 1. By using the toRefs function, because the above is equivalent to reactive processing, you can / / const {count, info} = toRefs (mainStore); / / 2. To solve the problem by using the storeToRefs method provided in pinia, it is recommended to use const {count, info} = storeToRefs (mainStore); const alertData = () = > {mainStore.count + = 10} 2.3 state data modification method (in actions and components)
General modification
Const alertData = () = > {/ / method 1: the simplest method is as follows: / / change mode after deconstruction / / count.value + = 10 / / change mode before structure / / mainStore.count + = 10 / / method 2: if you want to modify multiple data at the same time, it is recommended to use $patch to achieve batch update Internally optimized / / mainStore.$patch ({/ / count: mainStore.count + 1, / / info: "hello" / /}) / / method 3: better batch update method, which is realized by passing a function in $patch. Here the state is the state mainStore.$patch in the useMainStore container (state = > {state.count + = 10 state.info = "pinia batch update"})}
Modify via actions
/ / store/index.ts// is similar to the methods of vue2 components, which is used to encapsulate business logic and modify state// Note: you cannot use arrow functions to define actions Because the arrow function binds external this actions: {changeState () {this.count + = 10 this.info = "actions modify data"}, changeStates (num:number) {this.count + = num + 2 this.info = "actions modify data"}} const alertData = () = > {/ / way 1: the easiest way The following / / change mode after deconstruction / / count.value + = 10 / / change mode before structure / / mainStore.count + = 10 / / method 2: if you want to modify multiple data at the same time, it is recommended to use $patch to achieve batch update Internally optimized / / mainStore.$patch ({/ / count: mainStore.count + 1, / / info: "hello" / /}) / / method 3: better batch update method, which is realized by passing a function through $patch The state here is the state / / mainStore.$patch in the useMainStore container (state = > {/ / state.count + = 10 / / state.info = "pinia batch updates" / /}) / / way 4: modify the data mainStore.changeState () mainStore.changeStates (10)} 2.4 getters through actions
Define
/ / similar to the computed of the component, used to encapsulate the calculation properties. The cached function getters: {/ / function receives an optional parameter: state state object count10 (state) {return state.count + = 10}, count10 (state) {return this.count + = 10}, / / if this.count is used You must specify the type of data returned, count11 (): number {return this.count + = 11}}.
Use
{{mainStore.count10}} III. Pinia data persistence
Save to localStorage
Import {defineStore} from 'pinia';const useLoginStore = defineStore ({id:' login', / / state: () = > ({/ / num: 1, / /}), state: () > ({info: 'pinia can be used',}), getters: {}, actions: {alertInfo () {this.info ='OK, this second';},},}) / / data persistence / / 1. Save data const instance = useLoginStore (); instance.$subscribe ((_, state) = > {localStorage.setItem ('login-store', JSON.stringify ({... state}));}); / / 2. To get the saved data, first determine whether it is available or not, then use the previous const old = localStorage.getItem ('login-store'); if (old) {instance.$state = JSON.parse (old);} export default useLoginStore
Using the plug-in pinia-plugin-persist can assist in data persistence.
# install plug-in pnpm install pinia-plugin-persist-import {createPinia} from 'pinia';import {createApp} from' vue';import App from'. / App.vue';import router from'. / router';import piniaPluginPersist from 'pinia-plugin-persist';const pinia = createPinia (); pinia.use (piniaPluginPersist); const app = createApp (App); app.use (router); app.use (pinia); app.mount (' # app') in the save// main.ts file / / then open persist in the corresponding store. The data is stored in sessionStorage by default, and the id of store is used as key. Import {defineStore} from 'pinia';import piniaPluginPersist from' pinia-plugin-persist' Const useLoginStore = defineStore ({id: 'login', / / state: () = > ({/ / num: 1, / /}), state: () = > ({info:' pinia can be used',}), / / enable data cache persist: {enabled: true,}, getters: {}, actions: {alertInfo () {this.info = 'yes, this second' },},}) export default useLoginStore
Other settings, custom save name, save location and data to be saved
/ / enable data cache persist: {enabled: true, strategies: [{/ / Custom name key: 'login_store', / / Save location. Default is sessionStorage storage: localStorage, / / specify the data to be persisted. By default, all state are cached. You can specify the fields to be persisted through paths. Others are not persisted. Paths: ['age'],},],}, at this point, the study on "how to use Pinia for Vue3 state management" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.