


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

AI Hentai Generator
Generate AI Hentai for free.

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



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.

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.

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.

In Vue.js, lazy loading allows components or resources to be loaded dynamically as needed, reducing initial page loading time and improving performance. The specific implementation method includes using <keep-alive> and <component is> components. It should be noted that lazy loading can cause FOUC (splash screen) issues and should be used only for components that need lazy loading to avoid unnecessary performance overhead.

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the <script> tag in the HTML file that refers to the Vue file.

Implement marquee/text scrolling effects in Vue, using CSS animations or third-party libraries. This article introduces how to use CSS animation: create scroll text and wrap text with <div>. Define CSS animations and set overflow: hidden, width, and animation. Define keyframes, set transform: translateX() at the beginning and end of the animation. Adjust animation properties such as duration, scroll speed, and direction.

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.

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.
