


A brief analysis of how to use Pinia state management tool in Vue projects
VueHow to use Pinia state management tool in the project? The following article will talk about the use of Pinia state management tools in Vue projects. I hope it will be helpful to you!
Pinia official website says: Pinia is a repository for Vue that allows you to share state across components/pages. Vuex can also be used as a state management tool, so what is the difference between the two?
The difference between Pinia and Vuex
- Pinia only has stores, getters, actions, and no mutations, which simplifies the operation of state management. [Related recommendations: vuejs video tutorial, web front-end development]
- pinia module division does not require modules,
- pinia automated code splitting
- Pinia has good support for ts and the composition API of vue3
- Pinia is smaller in size and has better performance
Use Pinia
defineStore( )
The first parameter of the method: the name of the container, the name must be unique and cannot be repeateddefineStore( )
The second parameter of the method: configuration object, place state, getters, actionsstate
Attributes: Used to store the global stategetters
Attributes: Used to monitor or calculate state changes, with caching functionactions
Attribute: Modify state global state data, which can be asynchronous or synchronousPinia
Can be used in vue2.x or vue3.x
- Installation
yarn add pinia -S
-
main.js
Introduction
import {createApp} from "vue" import App from "./app.vue" import store from "./store/index.js" const app = createApp(App); const store = createPinia(); app.use(store).mount("#app")
- In the store file Create a new test.js under the folder
import {definePinia} from "pinia" export default testStore = definePinia('testId',{ state:()=>{ tname:"test", tnum:0, }, getters:{ changeTnum(){ console.log("getters") this.tnum++; } }, actions:{ addNum(val){ this.tnum += val } }, //持久化存储配置 presist:{ enable:true,// strategies:[ { key:"testId", storage:localStorage, paths:['tnum'] } ] } })
When using actions, you cannot use arrow functions because the arrow function binding is external this. This in actions points to the current store
- Create a new index.js under the store folder for easy management
import {createPinia} from "pinia" const store = createPinia(); export default store
- New
A.vue
component, introduces the store module andstoreToRefs
methodstoreToRefs
: Deconstruct the data instore
and make it responsive data
<template> <div> <div> {{tname}}</div> <div> {{tid}}</div> <div> tnum: {{tnum}}</div> <div> {{tchangeNum}}</div> <div><button @click="tchangeName">修改</button></div> <div> <button @click="treset">重置</button></div> <div @click="actionsBtn">actionsBtn</div> </div> </template>
<script setup> import { storeToRefs } from 'pinia' import { useStore } from '../store/user' import { useTest } from '../store/test.js' const testStore = useTest(); let { tname, tchangeNum, tnum } = storeToRefs(testStore) </script>
Two ways to directly modify data
Compared with using $path
to modify data directly, the official has made it clear$patch The
method is optimized and will speed up the modification, which is of great benefit to the performance of the program. So if you update status data with multiple pieces of data at the same time, it is recommended to use the $patch
method to update.
Although it can be modified directly, due to the code structure, global state management should not modify the state directly at each component. It should be modified in a unified method in actions
(piain does not have mutations) .
//直接修改数据 tchangeName(){ tname.value = "测试数据"; tnum.value++; } //当然也可以使用`$path`批量修改 tchangeName(){ testStore.$path(state=>{ state.tname = "测试数据"; state.value = 7; }) }
Use actions to modify data
Directly call the method in actions
, and you can pass parameters
const actionsBtn = (){ testStore.addNum(5) }
Reset the data in the state
## There is a$reset method in
#store, which can directly reset the data in
store
const treset = (){ testStore.$reset() }
- To achieve persistent storage, you need to use the following plug-in to use
yarn add pinia-plugin-persist
- to configure the
- index.js
file under the
storefolder. Introduce
pinia-plugin-presistplugin
import {createPinia} from "pinia" import piniaPluginPresist from "pinia-plugin-presist" const store = createPinia(); store.use(piniaPluginPresist) export default store
- Configure the test.js file under the stoe folder and use the
- presist
attribute to configure
import {definePinia} from "pinia" export default testStore = definePinia('testId',{ state:()=>{ tname:"test", tnum:0, }, getters:{ changeTnum(){ console.log("getters") this.tnum++; } }, actions:{ addNum(val){ this.tnum += val } }, //持久化存储配置 presist:{ enable:true,// strategies:[ { key:"testId", storage:localStorage, paths:['tnum'] } ] } })
- enable:true
, enable persistent storage, the default is to use
sessionStorageto store
-
strategies, proceed More configuration
-
key, when the key is not set, the key of storage is the first attribute of
definePinia. If the key value is set, the attribute name of storage is customized
- storage:localStorage
, set the cache mode to local storage
- paths
, if not set, the data used in
statewill be processed Persistence storage, when setting, only the set attributes are persistently stored
user.js file. Then the configuration content is the same as other modules, set according to your own needs, and then introduced on the corresponding page.
test.jsGet
user.js中
The name
attribute value of state is introduced in
test.js
user.js
import { defineStore } from 'pinia' import { userStore } from "./user.js" export const useTest = defineStore("testId", { state: () => { return { tid: "111", tname: "pinia", tnum: 0 } }, getters: { tchangeNum() { console.log('getters') return this.tnum + 100 } }, actions: { tupNum(val) { console.log('actions') this.tnum += val; }, getUserData() { console.log(useStore().name); return useStore().name; }, }, persist: { //走的session enabled: true, strategies: [ { key: "my_testId", storage: localStorage, paths: ['tnum'] } ] } })
user.js中
import { defineStore } from 'pinia' export const useStore = defineStore('storeId', { state: () => { return { num: 0, name: '张三' } } })
A.vue (学习视频分享:编程基础视频) The above is the detailed content of A brief analysis of how to use Pinia state management tool in Vue projects. For more information, please follow other related articles on the PHP Chinese website! component, call the
getUserData method in
test.js to get
uesr.js#name
value in ##
const actionBtn = () => {
testStore.getUserData()
};

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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.

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.

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.

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.

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.

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

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.

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.
