Pinia状态管理工具使用方法

171 阅读3分钟

前言

Pinia是尤雨溪强烈推荐的一款Vue状态管理工具,也被认为是下一代Vuex的替代产品。即Vuex5.x,在Vue3.0的项目中使用也是备受推崇。

Pinia

优点

  1. pinia没有mutations,只有:state、getters、actions。
  2. pinia分模块不需要modules(之前vuex分模块需要modules)。
  3. pinia体积更小(性能更好)。
  4. pinia可以直接修改state数据。

一、安装使用Pinia

1.1安装下载

yarn add pinia
# or with npm
npm install pinia

1.2main.js引入

import { createPinia } from 'pinia'

app.use(createPinia())

1.3 在根目录下新建store/index.js中写入

import { defineStore } from 'pinia'

export const useStore = defineStore('storeId', {
  state() => {
    return {
      num0,
    }
  },
  getters:{},
  actions:{}
})

1.4 在组件中使用

<script setup>
import { useStore } from '../store'
const store = useStore();
</script>

二、State

2.1 Pinia定义state数据

import { defineStore } from 'pinia'
export const useStore = defineStore('storeId', {
  state() => {
    return {
      name'前端诡刺',
      age18,
      sex'男',
    }
  },
  getters:{},
  actions:{}
})

2.2 组件使用pinia的state数据

<template>
 <div>
  <h1>A组件</h1>
  {{ name }}
 </div>
</template>
<script setup>
import { useStore } from '../store'
const store = useStore();
let { name } = store;
</script>

2.3 组件修改pinia的state数据

本身pinia可以直接修改state数据,无需像vuex一样通过mutations才可以修改,但是上面写的let { name } = store;这种解构是不可以的,所以要换解构的方式。

<template>
 <div>
  <h1>A组件</h1>
  {{ name }}
  <button @click='btn'>按钮</button>
 </div>
</template>
<script setup>
import { storeToRefs } from 'pinia'
import { useStore } from '../store'
const store = useStore();
let { name }  = storeToRefs(store);
const btn = ()=>{
 name.value = '前端菜鸟';
}
</script>

2.4 如果state数据需要批量更新

store/index.js

import { defineStore } from 'pinia'
export const useStore = defineStore('storeId', {
  state() => {
    return {
      name'前端诡刺',
      age18,
    }
  },
  getters:{},
  actions:{}
})

组件代码

<template>
 <div>
  <h1>A组件</h1>
  {{ name }}
  {{ age }}
  <button @click='btn'>按钮</button>
 </div>
</template>
<script setup>
import { storeToRefs } from 'pinia'
import { useStore } from '../store'
const store = useStore();
let { name,age }  = storeToRefs(store);
const btn = ()=>{
 //批量更新
 store.$patch(state=>{
  state.name = '前端菜鸟';
  state.age = 20;
 })
}
</script>

三、actions

actions相当于methods,里面可以写方法,例如写个带参数的加等方法

store/index.js

import { defineStore } from 'pinia'
export const useStore = defineStore('storeId', {
  state() => {
    return {
      num0
    }
  },
  getters:{},
  actions:{
   changeNum( val ){
    this.num += val;
   }
  }
})

组件中使用

<template>
 <div>
  <h1>A组件</h1>
  {{ num }}
  <button @click='add'>+1</button>
 </div>
</template>
<script setup>
import { storeToRefs } from 'pinia'
import { useStore } from '../store'
const store = useStore();
let { num }  = storeToRefs(store);
const add = ()=>{
 store.changeNum(1);
}
</script>

四、getters

getters相当于computed,可以对数据进行处理

import { defineStore } from 'pinia'
export const useStore = defineStore('storeId', {
  state() => {
    return {
      num0,
    }
  },
  getters:{
   numAdd(){
    return this.num + 1;
   }
  },
  actions:{}
})

组件中使用

<template>
 <div>
  <h1>A组件</h1>
  {{ num }}
  {{ num }}
  {{ numAdd }}
 </div>
</template>
<script setup>
import { storeToRefs } from 'pinia'
import { useStore } from '../store'
const store = useStore();
let { num, numAdd }  = storeToRefs(store);
</script>

以上是Pinia的使用方法,有一个问题就是页面刷新后,所有的数据都会恢复成默认状态,为了解决这个问题,接下来给大家介绍一款数据持久化插件(pinia-plugin-persist),当然了有能力的可以自己封装一个。

pinia-plugin-persist

一、安装插件

npm i pinia-plugin-persist --save

二、使用

store/index.js

import { createPinia } from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist'
const store = createPinia()
store.use(piniaPluginPersist)
export default store

store/user.js

export const useUserStore = defineStore({
  id'user',
  state() => {
    return {
      name'前端诡刺'
    }
  },
  // 开启数据缓存
  persist: {
    enabledtrue
  }
})

三、自定义储存方式及key值

store/user.js

export const useUserStore = defineStore({
  id'user',
  state() => {
    return {
      name'前端诡刺'
    }
  },
  // 开启数据缓存
  persist: {
    enabledtrue,
    strategies: [
    {
      key'myUser',//储存到浏览器中的key值,默认会以store的id作为key
      storagelocalStorage,//储存方式不指定的话默认储存sessionStorage中
    }
  ]
  }
})

四、持久化局部state

默认所有 state 都会进行缓存,你能够通过 paths 指定要长久化的字段,其余的则不会进行长久化。

store/user.js

export const useUserStore = defineStore({
  id'user',
  state() => {
    return {
      name'前端诡刺',
      age:18,
      sex:'男'
    }
  },
  // 开启数据缓存
  persist: {
    enabledtrue,
    strategies: [
    {
      storagelocalStorage,
      paths: ['name''age']
    }
  ]
  }
})

总结

到这里pinia使用就介绍完了,相信大家应该不陌生了,关注我,后续持续更新,快动手实操一下吧,眼会≠学会。 以上分享仅为自己的见解(不喜勿喷),若有误或者你有更好的方法,欢迎来评论指出。

如果这篇文章对你来说有点作用,欢迎点赞、关注、收藏,避免在需要的时候找不到。

如果文中有错误,欢迎指正~

更多优质文章请关注微信公众号【前端诡刺】