软件系统定制开发科技与狠活儿丨Vue项目中Pinia状态管理工具的使用

目录


软件系统定制开发官网介绍说:Pinia 是 Vue 的存储库,软件系统定制开发它允许您跨组件/软件系统定制开发页面共享状态。Vuex软件系统定制开发同样可以作为状态管理工具,软件系统定制开发那么两者有什么区别呢?

Pinia与Vuex的区别

  • pinia只有store、getter、actions,么有mutations,简化了状态管理的操作
  • pinia模块划分不需要modules,
  • pinia自动化代码拆分
  • pinia对ts支持很好以及vue3的composition API
  • pinia体积更小,性能更好

使用Pinia

defineStore( ) 方法的第一个参数:容器的名字,名字必须唯一,不能重复
defineStore( ) 方法的第二个参数:配置对象,放置state,getters,actions
state 属性: 用来存储全局的状态
getters属性: 用来监视或者说是计算状态的变化的,有缓存的功能
actions属性: 修改state全局状态数据,可以是异步也可以是同步
Pinia可以用于vue2.x也可以用于vue3.x中

  • 安装
yarn add pinia -S
  • 1
  • main.js引入
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")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 在store文件夹下新建test.js
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']            }          ]    }})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

在用actions的时候,不能使用箭头函数,因为箭头函数绑定是外部的this。actions里的this指向当前store

  • 在store文件夹下新建index.js,便于管理
import {createPinia} from "pinia"const store = createPinia();export default store
  • 1
  • 2
  • 3
  • 新建A.vue组件,引入store模块和storeToRefs方法
    storeToRefs:解构store中的数据,使之成为响应式数据
<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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
<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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

直接修改数据的两种方式

直接修改数据与使用$path修改数据相比,官方已经明确表示$patch的方式是经过优化的,会加快修改速度,对程序的性能有很大的好处。所以如果你是多条数据同时更新状态数据,推荐使用$patch方式更新。
虽然可以直接修改,但是出于代码结构来说, 全局的状态管理还是不要直接在各个组件处随意修改状态,应放于actions中统一方法修改(piain没有mutation)。

//直接修改数据tchangeName(){     tname.value = "测试数据";     tnum.value++;}//当然也可以使用`$path`批量修改tchangeName(){     testStore.$path(state=>{          state.tname = "测试数据";          state.value = 7;     })}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

使用actions修改数据

直接调用actions中的方法,可传参数

const actionsBtn = (){      testStore.addNum(5)  }
  • 1
  • 2
  • 3

重置state中数据

store中有$reset方法,可以直接对store中数据重置

const treset = (){    testStore.$reset()}
  • 1
  • 2
  • 3

Pinia持久化存储

  • 实现持久化存储,需要配合以下插件使用
yarn add  pinia-plugin-persist
  • 1
  • 配置store文件夹下的index.js文件,引入pinia-plugin-presist插件
import {createPinia} from "pinia"import piniaPluginPresist from "pinia-plugin-presist"const store = createPinia();store.use(piniaPluginPresist)export default store
  • 1
  • 2
  • 3
  • 4
  • 5
  • 配置stroe文件夹下的test.js文件,使用presist属性进行配置
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']            }          ]    }})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • enable:true,开启持久化存储,默认为使用sessionStorage存储
    - strategies,进行更多配置
    - key,不设置key时,storage的key为definePinia的第一个属性,设置key值,则自定义storage的属性名
  • storage:localStorage,设置缓存模式为本地存储
  • paths,不设置时对state中的所用数据进行持久化存执,设置时只针对设置的属性进行持久化存储

Pinia模块化实现

模块化实现即在store对要使用的模块新建一个js文件,比如user.js文件。然后配置内容跟其他模块一样,根据自己需求进行设置,然后在对应页面引入。

Pinia中store之间互相调用

比如:test.js获取user.jsstatename属性值,在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']			}		]	}})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

user.js

import { defineStore } from 'pinia'export const useStore = defineStore('storeId', {  state: () => {    return {      num: 0,      name: '张三'    }  }})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

A.vue组件中,调用test.jsgetUserData方法就可以得到uesr.js中的name

const actionBtn = () => {    testStore.getUserData()};
  • 1
  • 2
  • 3
网站建设定制开发 软件系统开发定制 定制软件开发 软件开发定制 定制app开发 app开发定制 app开发定制公司 电商商城定制开发 定制小程序开发 定制开发小程序 客户管理系统开发定制 定制网站 定制开发 crm开发定制 开发公司 小程序开发定制 定制软件 收款定制开发 企业网站定制开发 定制化开发 android系统定制开发 定制小程序开发费用 定制设计 专注app软件定制开发 软件开发定制定制 知名网站建设定制 软件定制开发供应商 应用系统定制开发 软件系统定制开发 企业管理系统定制开发 系统定制开发