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

青灯夜游
青灯夜游forward
2022-11-07 20:09:511607browse

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
  • 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")
  • 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
  • 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>
<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>

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;
     })
}

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()
}

Pinia persistent storage

    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 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
    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;]
                } 
             ]
        }
    })
  • 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;]
			}
		]
	}
})

user.js

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

A.vue component, call the getUserData method in test.js to get uesr.js#name value in ##<pre class="brush:js;toolbar:false;">const actionBtn = () =&gt; { testStore.getUserData() };</pre><p>(学习视频分享:<a href="https://www.php.cn/course/list/91.html" target="_blank" textvalue="编程基础视频">编程基础视频</a>)<br></p>

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:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete