【小番茄夫斯基】Pinia状态管理

2023-05-16

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

优点

  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 {
      num: 0,
    }
  },
  getters:{},
  actions:{}
})

1.4 在组件中使用

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

二,pinia中 state的用法

2.1 Pinia定义state数据

import { defineStore } from 'pinia'
export const useStore = defineStore('storeId', {
  state: () => {
    return {
      name: '前端诡刺',
      age: 18,
      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: '前端诡刺',
      age: 18,
    }
  },
  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>

三,pinia中 actions 的使用

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

store/index.js

import { defineStore } from 'pinia'
export const useStore = defineStore('storeId', {
  state: () => {
    return {
      num: 0
    }
  },
  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>

四,pinia中 getters 的使用

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

import { defineStore } from 'pinia'
export const useStore = defineStore('storeId', {
  state: () => {
    return {
      num: 0,
    }
  },
  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: {
    enabled: true
  }
})

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

store/user.js

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

四、持久化局部state

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

store/user.js

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

pinia和vuex的区别

  1. pinia它没有mutation,他只有state,getters,action【同步、异步】使用他来修改state数据
  2. pinia他默认也是存入内存中,如果需要使用本地存储,在配置上比vuex麻烦一点
  3. pinia语法上比vuex更容易理解和使用,灵活。
  4. pinia没有modules配置,没一个独立的仓库都是definStore生成出来的
  5. pinia state是一个对象返回一个对象和组件的data是一样的语法

Vuex 和 Pinia 的优缺点

Pinia的优点

  • 完整的 TypeScript 支持:与在 Vuex 中添加 TypeScript 相比,添加 TypeScript 更容易
  • 极其轻巧(体积约 1KB)
  • store 的 action 被调度为常规的函数调用,而不是使用 dispatch 方法或 MapAction 辅助函数,这在 Vuex 中很常见
  • 支持多个Store
  • 支持 Vue devtools、SSR 和 webpack 代码拆分

Pinia的缺点

不支持时间旅行和编辑等调试功能

Vuex的优点

支持调试功能,如时间旅行和编辑
适用于大型、高复杂度的Vue.js项目

Vuex的缺点

  • 从 Vue 3 开始,getter 的结果不会像计算属性那样缓存
  • Vuex 4有一些与类型安全相关的问题

何时使用Pinia,何时使用Vuex

个人感觉:,由于Pinea是轻量级的,体积很小,它适合于中小型应用。它也适用于低复杂度的Vue.js项目,因为一些调试功能,如时间旅行和编辑仍然不被支持。
将 Vuex 用于中小型 Vue.js 项目是过度的,因为它重量级的,对性能降低有很大影响。因此,Vuex 适用于大规模、高复杂度的 Vue.js 项目。

pinia和vuex在vue2和vue3都可以使用,一般来说vue2使用vuex,vue3使用pinia。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【小番茄夫斯基】Pinia状态管理 的相关文章

随机推荐

  • java中的异常处理

    异常概述 异常的作用 xff1a 增强程序的健壮性 java中异常以什么形式存在 xff1f 异常在java中以类的形式存在 xff0c 每一个异常类都可以创建异常对象 JVM执行到某一处觉得有异常 xff0c 会new异常对象 xff0c
  • 人工智能在医学影像中的研究与应用

    人工智能在医学影像中的研究与应用 韩冬 李其花 蔡巍 夏雨薇 宁佳 黄峰 沈阳东软医疗系统有限公司 xff0c 辽宁 沈阳 110167 慧影医疗科技 xff08 北京 xff09 有限公司 xff0c 北京 100192 东软集团股份有限
  • 开始

    文章目录 徐工本科生 希望明天更好 xff0c 今天开始扬帆起航 新的改变功能快捷键合理的创建标题 xff0c 有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中 居左 居右
  • Linux-生产者消费者模型

    生产者消费者模型 生产者消费者模型概念生产者消费者模型特点生产者消费者模型优点基于BlockingQueue的生产者消费者模型基于阻塞队列的生产者消费者模型 模拟实现生产者消费者模型多生产者和多消费者 生产者消费者模型概念 生产者消费者模型
  • Ubuntu20.04下更新系统Python版本

    起因 xff1a 写Python时报错 xff1a TypeError unsupported operand type s for 61 dict and dict 原因 xff1a python3 9 支持对 dict 类型使用 xff
  • Ubuntu密码忘记怎么办

    1 重启Ubuntu xff0c 长按shift出现以下界面 xff0c 按回车键 2 紧接着进入如下界面 xff0c 选中recovery mode的选项 xff0c 按 e 进入界面 xff0c 务必记得不要按enter键 3 找到下图
  • 小程序视频截gif_3个简单的应用程序,可让您深入视频和GIF

    小程序视频截gif Deepfakes make it possible to manipulate videos and GIFs The technology has become so easy to use you can now
  • Spring框架详解(建议收藏)

    1 什么是Spring xff1f 官网 xff1a https spring io 侠义的Spring是指Spring框架 xff08 Spring Fremework xff09 https spring io projects spr
  • Debian (Linux)安装UFW防火墙

    Debian Linux 安装UFW防火墙 1ufw简介 UFW xff0c 即简单防火墙 xff0c 是iptables的接口 xff0c 旨在简化防火墙的配置过程 尽管iptables是可靠且灵活的工具 xff0c 但对于初学者而言 x
  • 高性能动画JSON动画

    animejs 它是一个js动画库 xff0c 是对transform进行封装 xff0c 使其受js控制 拥有更高性能和很好的兼容 最重要的是 xff1a 提供了很多回调 监听方法 eg 每帧回调 每次循环回调 循环开始的回调 提供了一个
  • C++ 生产者消费者示例代码

    三部分构成 xff1a 生产者 消费者 仓储 span class token macro property span class token directive keyword include span span class token
  • 7-1 将数组中的数逆序存放 (15 分)

    7 1 将数组中的数逆序存放 15 分 本题要求编写程序 xff0c 将给定的n个整数存入数组中 xff0c 将数组中的这n个数逆序存放 xff0c 再按顺序输出数组中的元素 输入格式 输入在第一行中给出一个正整数n xff08 1 n 1
  • JavaFX学习笔记(最全,最详细)

    文章目录 Java JavaFX桌面GUI开发1 基本概念2 最小框架代码3 控件布局4 xff0c 初步认识stage窗口5 xff0c stage窗口模式 StageStyle 6 xff0c screen类的使用7 xff0c Gro
  • vue3安装和开发环境搭建

    文章目录 一 xff0c 简介二 xff0c vue cil 搭建 vue3 开发环境三 xff0c 增加typescipt 一 xff0c 简介 二 xff0c vue cil 搭建 vue3 开发环境 1 xff0c 安装 xff1a
  • 使用vite创建vue项目和使用vue-cli创建项目的区别

    文章目录 一 xff0c 介绍二 xff0c vite创建项目介绍三 xff0c vue cli创建项目介绍 xff08 1 xff09 安装升级 xff08 2 xff09 创建项目 一 xff0c 介绍 Vite 是一个 web 开发构
  • vue3中的组件通信【2】《爷孙组件通信》

    文章目录 爷孙组件通信provide inject响应性数据的传递与接收 爷孙组件通信 顾名思义 xff0c 爷孙组件是比 父子组件通信 要更深层次的引用关系 xff08 也有称之为 隔代组件 xff09 xff1a Grandfather
  • 大前端知识图谱+B站视频整合

    文章目录 前端学习路径B站视频整合网络知识超文本标记语言层叠样式表浏览器脚本语言 https www bilibili com video BV1Sy4y1C7ha https www bilibili com video BV1Sy4y1
  • 电台复活节_如何玩Android 11的隐藏复活节彩蛋游戏

    电台复活节 Justin Duino 贾斯汀 杜伊诺 Justin Duino Google includes a hidden Easter Egg with each new Android version Android 11 has
  • 【小番茄夫斯基】全网最全前端面试手撕算法题,原理手写汇总

    文章目录 深拷贝柯里化函数实现 instanceof手写 new数组去重flat 拍平数组ObjectDefineProperty实现双向数据绑定setInterval 实现 setTimeoutsetTimeout 实现 setInter
  • 【小番茄夫斯基】Pinia状态管理

    Pinia是尤雨溪强烈推荐的一款Vue状态管理工具 xff0c 也被认为是下一代Vuex的替代产品 即Vuex5 x xff0c 在Vue3 0的项目中使用也是备受推崇 优点 pinia没有mutations xff0c 只有 xff1a