Table of Contents
The difference between Pinia and Vuex
Use Pinia
Two ways to directly modify data
Use actions to modify data
Reset the data in the state
Home Web Front-end Vue.js A brief analysis of how to use Pinia state management tool in Vue projects

A brief analysis of how to use Pinia state management tool in Vue projects

Nov 07, 2022 pm 08:09 PM
vue pinia

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!

A brief analysis of how to use Pinia state management tool in Vue projects

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?
A brief analysis of how to use Pinia state management tool in Vue projects

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 repeated
defineStore( ) The second parameter of the method: configuration object, place state, getters, actions
state Attributes: Used to store the global state
gettersAttributes: Used to monitor or calculate state changes, with caching function
actionsAttribute: Modify state global state data, which can be asynchronous or synchronous
PiniaCan be used in vue2.x or vue3.x

  • Installation
yarn add pinia -S
Copy after login
  • main.jsIntroduction
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")
Copy after login
  • 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']
            } 
         ]
    }
})
Copy after login
Copy after login

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
Copy after login
  • NewA.vue component, introduces the store module and storeToRefs method
    storeToRefs: Deconstruct the data in store 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>
Copy after login
<script setup>
import { storeToRefs } from &#39;pinia&#39;
import { useStore } from &#39;../store/user&#39;
import { useTest } from &#39;../store/test.js&#39;
const testStore = useTest();
let { tname, tchangeNum, tnum } = storeToRefs(testStore)
</script>
Copy after login

Two ways to directly modify data

Compared with using $pathto 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;
     })
}
Copy after login

Use actions to modify data

Directly call the method in actions, and you can pass parameters

const actionsBtn = (){
      testStore.addNum(5)  
}
Copy after login

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()
}
Copy after login

Pinia persistent storage

    To achieve persistent storage, you need to use the following plug-in to use
  • yarn add  pinia-plugin-persist
    Copy after login
    to configure the
  • index.js file under the store folder. Introduce pinia-plugin-presistplugin
  • import {createPinia} from "pinia"
    import piniaPluginPresist from "pinia-plugin-presist"
    const store = createPinia();
    store.use(piniaPluginPresist)
    export default store
    Copy after login
    Configure the test.js file under the stoe folder and use the
  • presist attribute to configure
  • import {definePinia} from "pinia"
    export default testStore = definePinia(&#39;testId&#39;,{
        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:[&#39;tnum&#39;]
                } 
             ]
        }
    })
    Copy after login
    Copy after login
  • enable:true, enable persistent storage, the default is to use sessionStorage to 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 state will be processed Persistence storage, when setting, only the set attributes are persistently stored
Pinia modular implementation

Modular implementation means creating a new js file in the store for the module to be used , such as

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.
A brief analysis of how to use Pinia state management tool in Vue projects

The stores in Pinia call each other

For example:

test.jsGetuser.js The name attribute value of state is introduced in test.js user.js

import { defineStore } from &#39;pinia&#39;
import { userStore } from "./user.js"
export const useTest = defineStore("testId", {
	state: () => {
		return {
			tid: "111",
			tname: "pinia",
			tnum: 0
		}
	},
	getters: {
		tchangeNum() {
			console.log(&#39;getters&#39;)
			return this.tnum + 100
		}
	},
	actions: {
		tupNum(val) {
			console.log(&#39;actions&#39;)
			this.tnum += val;
		},
		getUserData() {
			console.log(useStore().name);
			return useStore().name;
		},
	},
	persist: {
		//走的session
		enabled: true,
		strategies: [
			{
				key: "my_testId",
				storage: localStorage,
				paths: [&#39;tnum&#39;]
			}
		]
	}
})
Copy after login

user.js

import { defineStore } from &#39;pinia&#39;
export const useStore = defineStore(&#39;storeId&#39;, {
  state: () => {
    return {
      num: 0,
      name: &#39;张三&#39;
    }
  }
})
Copy after login

A.vue component, call the getUserData method in test.js to get uesr.js#name value in ##

const actionBtn = () => {
    testStore.getUserData()
};
Copy after login

(学习视频分享:编程基础视频

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

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.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

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.

What does it mean to lazy load vue? What does it mean to lazy load vue? Apr 07, 2025 pm 11:54 PM

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 &lt;keep-alive&gt; and &lt;component is&gt; 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.

How to query the version of vue How to query the version of vue Apr 07, 2025 pm 11:24 PM

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 &lt;script&gt; tag in the HTML file that refers to the Vue file.

Vue realizes marquee/text scrolling effect Vue realizes marquee/text scrolling effect Apr 07, 2025 pm 10:51 PM

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 &lt;div&gt;. 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.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

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.

See all articles