本文为转载文
作者:小学生study
链接:https://juejin.cn/post/704919...

前言

Pinia.js 是新一代的状态管理器,由 Vue.js团队中成员所开发的,因而也被认为是下一代的 Vuex,即 Vuex5.x,在 Vue3.0 的我的项目中应用也是备受推崇。

Pinia.js 有如下特点:

  • 残缺的 typescript 的反对;
  • 足够轻量,压缩后的体积只有1.6kb;
  • 去除 mutations,只有 state,getters,actions(这是我最喜爱的一个特点);
  • actions 反对同步和异步;
  • 没有模块嵌套,只有 store 的概念,store 之间能够自在应用,更好的代码宰割;
  • 无需手动增加 store,store 一旦创立便会主动增加;

装置

npm install pinia --save复制代码

创立 Store

新建 src/store 目录并在其上面创立 index.ts,导出 store

// src/store/index.tsimport { createPinia } from 'pinia'const store = createPinia()export default store复制代码

在 main.ts 中引入并应用。

// src/main.tsimport { createApp } from 'vue'import App from './App.vue'import store from './store'const app = createApp(App)app.use(store)复制代码

State

定义State

在 src/store 上面创立一个user.ts

//src/store/user.tsimport { defineStore } from 'pinia'export const useUserStore = defineStore({  id: 'user',  state: () => {    return {      name: '张三'    }  }})复制代码

获取 state

<template>  <div>{{ userStore.name }}</div></template><script lang="ts" setup>import { useUserStore } from '@/store/user'const userStore = useUserStore()</script>复制代码

也能够联合 computed 获取。

const name = computed(() => userStore.name)复制代码

state 也能够应用解构,但应用解构会使其失去响应式,这时候能够用 pinia 的 storeToRefs

import { storeToRefs } from 'pinia'const { name } = storeToRefs(userStore)复制代码

批改 state

能够像上面这样间接批改 state

userStore.name = '李四'复制代码

但个别不倡议这么做,倡议通过 actions 去批改 state,action 里能够间接通过 this 拜访。

export const useUserStore = defineStore({  id: 'user',  state: () => {    return {      name: '张三'    }  },  actions() {    updateName(name) {      this.name = name    }  }})复制代码
<script lang="ts" setup>import { useUserStore } from '@/store/user'const userStore = useUserStore()userStore.updateName('李四')</script>复制代码

Getters

export const useUserStore = defineStore({ id: 'user', state: () => {   return {     name: '张三'   } }, getters: {   fullName: (state) => {     return state.name + '丰'   } }})复制代码
userStore.fullName // 张三丰复制代码

Actions

异步 action

action 能够像写一个简略的函数一样反对 async/await 的语法,让你欢快的应酬异步解决的场景。

export const useUserStore = defineStore({  id: 'user',  actions() {    async login(account, pwd) {      const { data } = await api.login(account, pwd)      return data    }  }})复制代码

action 间互相调用

action 间的互相调用间接用 this 拜访即可。

 export const useUserStore = defineStore({  id: 'user',  actions() {    async login(account, pwd) {      const { data } = await api.login(account, pwd)      this.setData(data) // 调用另一个 action 的办法      return data    },    setData(data) {      console.log(data)    }  }})复制代码

在 action 里调用其余 store 里的 action 也比较简单,引入对应的 store 后即可办法其 action 的办法了。

// src/store/user.tsimport { useAppStore } from './app'export const useUserStore = defineStore({  id: 'user',  actions() {    async login(account, pwd) {      const { data } = await api.login(account, pwd)      const appStore = useAppStore()      appStore.setData(data) // 调用 app store 里的 action 办法      return data    }  }})复制代码
// src/store/app.tsexport const useAppStore = defineStore({  id: 'app',  actions() {    setData(data) {      console.log(data)    }  }})复制代码

数据长久化

插件 pinia-plugin-persist 能够辅助实现数据长久化性能。

装置

npm i pinia-plugin-persist --save复制代码

应用

// src/store/index.tsimport { createPinia } from 'pinia'import piniaPluginPersist from 'pinia-plugin-persist'const store = createPinia()store.use(piniaPluginPersist)export default store复制代码

接着在对应的 store 里开启 persist 即可。

export const useUserStore = defineStore({  id: 'user',  state: () => {    return {      name: '张三'    }  },    // 开启数据缓存  persist: {    enabled: true  }})复制代码

数据默认存在 sessionStorage 里,并且会以 store 的 id 作为 key。

自定义 key

你也能够在 strategies 里自定义 key 值,并将寄存地位由 sessionStorage 改为 localStorage。

persist: {  enabled: true,  strategies: [    {      key: 'my_user',      storage: localStorage,    }  ]}复制代码

长久化局部 state

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

state: () => {  return {    name: '张三',    age: 18,    gender: '男'  }  },persist: {  enabled: true,  strategies: [    {      storage: localStorage,      paths: ['name', 'age']    }  ]}复制代码

下面咱们只长久化 name 和 age,并将其改为localStorage, 而 gender 不会被长久化,如果其状态发送更改,页面刷新时将会失落,从新回到初始状态,而 name 和 age 则不会。

感激

本次分享到这里就完结了,感谢您的浏览,如果本文对您有什么帮忙,别忘了动动手指导个赞❤️。

本文如果有什么谬误或有余,欢送评论区斧正!

结语

我是林三心,一个热心的前端菜鸟程序员。如果你上进,喜爱前端,想学习前端,那咱们能够交朋友,一起摸鱼哈哈,摸鱼群,加我请备注【思否】