位置: IT常识 - 正文

Vue状态管理--Pinia使用详解(vue状态管理有哪些)

编辑:rootadmin
Vue状态管理--Pinia使用详解 一、Pinia概述

推荐整理分享Vue状态管理--Pinia使用详解(vue状态管理有哪些),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:vue状态管理工具有哪些,vue状态管理工具有哪些,vue状态管理pinia,vue状态管理是什么,vue状态管理工具,vue状态管理库 pinia,vue状态管理是什么,vue状态管理库 pinia,内容如对您有帮助,希望把文章链接给更多的朋友!

Pinia开始于大概2019年,最初作为一个实验为Vue重新设计状态管理,让它用起来像组合API。

Pinia本质上依然是一个状态管理的库,用于跨组件、页面进行状态共享(这点和Vuex、Redux一样)。

Pinia(发音为/piːnjʌ/,如英语中的peenya)是最接近piña(西班牙语中的菠萝)的词。

这可能也是Pinia的图标是一个菠萝的原因。

二、Pinia和Vuex的区别

Pinia最初是为了探索 Vuex 的下一次迭代会是什么样子,结合了 Vuex 5 核心团队讨论中的许多想法。

最终,团队意识到Pinia已经实现了Vuex5中大部分内容,所以最终决定用Pinia来替代Vuex。

和Vuex相比,Pinia有很多的优势:

mutations不再存在

更友好的TypeScript支持,Vuex之前对TS的支持很不友好

不再有modules的嵌套结构,可以灵活使用每一个store,它们是通过扁平化的方式来相互使用的

不再有命名空间的概念,不需要记住它们的复杂关系

三、Pinia的安装和基本配置3.1 安装Pinia# npm 方式npm install pinia# yarn 方式yarn add pinia3.2 创建一个pinia并且将其传递给应用程序1)新建store文件夹,在此文件夹下新建一个index.jsimport { createPinia } from 'pinia'//创建一个pinia实例const pinia = createPinia()export default pinia2)在main.js中use它import { createApp } from 'vue'import App from './App.vue'import pinia from './stores'createApp(App).use(pinia).mount('#app')

完成上述代码后,pinia在项目中就生效了

四、Pinia中的Store4.1 什么是Store?

一个Store (如Pinia)是一个实体,它会持有绑定到你组件树的状态和业务逻辑,即保存了全局的状态;

它有点像始终存在,并且每个人都可以读取和写入的组件;

你可以在你的应用程序中定义任意数量的Store来管理你的状态;

Store有三个核心概念: state、getters、actions。

等同于组件的data、computed、methods。

一旦 store 被实例化,你就可以直接在 store 上访问 state、getters 和 actions中定义的任何属性。

4.2 如何定义一个storeVue状态管理--Pinia使用详解(vue状态管理有哪些)

定义之前需要知道:

store 是使用 defineStore() 定义的

并且它需要一个唯一名称,作为第一个参数传递

这个 唯一名称name,也称为 id,是必要的,Pinia 使用它来将 store 连接到 devtools

返回的函数统一使用useX作为命名方案,这是约定的规范

具体示例:

定义一个counter.js,在里面定义一个store

// 定义关于counter的storeimport { defineStore } from 'pinia'const useCounter = defineStore("counter", { // 在 Pinia 中,状态被定义为返回初始状态的函数 state: () => ({ count: 99 })})export default useCounter

这里有一个注意点,就是defineStore函数的返回值的命名规则:

以use开头,加上传给defineStore函数的第一个参数组成,使用驼峰命名法。

这虽然不是强制,确是一个大家都遵守的规范。

4.3 使用store读取和写入 state:<template> <div class="home"> <h2>Home View</h2> <!-- 2.使用useCounter的实例获取state中的值 --> <h2>count: {{ counterStore.count }}</h2> <h2>count: {{ count }}</h2> </div></template><script setup> import useCounter from '@/stores/counter'; import { storeToRefs } from 'pinia' // 1.直接使用useCounter获取counter这个Store的实例 // 这个函数名称取决于defineStore的返回值 const counterStore = useCounter() // 使用storeToRefs对数据进行结构,让count保持响应式的效果 const { count } = storeToRefs(counterStore) // 3.修改(写入)store counterStore.count++ </script>

store在它被使用之前是不会创建的,我们可以通过调用use函数来使用store。

Pinia中可以直接使用store实例去修改state中的数据,非常方便。

注意:

store获取到后不能被解构,因为会让数据失去响应式。

为了从 store中提取属性同时保持其响应式,需要使用storeToRefs()。

4.4 修改state的多种方式

1)定义一个关于user的Store

import { defineStore } from 'pinia'const useUser = defineStore("user", { state: () => ({ name: "why", age: 18, level: 100 })})export default useUser

2)三种修改state的方式

<script setup> import useUser from '@/stores/user' import { storeToRefs } from 'pinia'; const userStore = useUser() const { name, age, level } = storeToRefs(userStore) function changeState() { // 1.一个个修改状态 // userStore.name = "kobe" // userStore.age = 20 // userStore.level = 200 // 2.一次性修改多个状态 // userStore.$patch({ // name: "james", // age: 35 // }) // 3.替换state为新的对象 const oldState = userStore.$state userStore.$state = { name: "curry", level: 200 } // 下面会返回true console.log(oldState === userStore.$state) }</script>4.5 重置store<script> import useCounter from '@/stores/counter'; const counterStore = useCounter() counterStore.$reset()</script>五、getters的使用

Getters相当于Store的计算属性:

它可以用defineStore()中的getters属性定义;

getters中可以定义接受一个state作为参数的函数;

5.1 定义getters// 定义关于counter的storeimport { defineStore } from 'pinia'const useCounter = defineStore("counter", { state: () => ({ count: 99 }), getters: { // 基本使用 doubleCount(state) { return state.count * 2 }, // 2.一个getter引入另外一个getter doubleCountAddOne() { // this是store实例,可以直接使用另一个getter return this.doubleCount + 1 }, // 3.getters也支持返回一个函数 getFriendById(state) { return function(id) { for (let i = 0; i < state.friends.length; i++) { const friend = state.friends[i] if (friend.id === id) { return friend } } } }, },})export default useCounter5.2 访问getters<template> <div class="home"> <!-- 在模板中使用 --> <h2>doubleCount: {{ counterStore.doubleCount }}</h2> <h2>doubleCountAddOne: {{ counterStore.doubleCountAddOne }}</h2> <h2>friend-111: {{ counterStore.getFriendById(111) }}</h2> </div></template><script setup> import useCounter from '@/stores/counter'; const counterStore = useCounter() // 在js文件中使用 const doubleCount = counterStore.doubleCount; const doubleCountAddOne = counterStore.doubleCountAddOne; const frend = counterStore.getFriendById(111)</script>5.3 getters中获取另一个store中的state/getters数据// 定义关于counter的storeimport { defineStore } from 'pinia'// 引入另一个storeimport useUser from './user'const useCounter = defineStore("counter", { state: () => ({ count: 99, }), getters: { // 4.getters中用到别的store中的数据 showMessage(state) { // 1.获取user信息 const userStore = useUser() // 2.获取自己的信息 // 3.拼接信息(使用另一个store中的数据) return `name:${userStore.name}-count:${state.count}` } }})export default useCounter六、actions的使用

actions 相当于组件中的 methods。

可以使用defineStore()中的actions属性定义,并且它们非常适合定义一些业务逻辑。

和getters一样,在action中可以通过this访问整个store实例的所有操作。

6.1 基本定义方式// 定义关于counter的storeimport { defineStore } from 'pinia'const useCounter = defineStore("counter", { state: () => ({ count: 99, }), // 定义actions actions: { increment() { this.count++ }, incrementNum(num) { this.count += num } }})export default useCounter6.2 基本使用方式<template> <div class="home"> <h2>doubleCount: {{ counterStore.count }}</h2> <button @click="changeState">修改state</button> </div></template><script setup> import useCounter from '@/stores/counter'; const counterStore = useCounter() function changeState() { // 可以通过counterStore对象直接使用 // counterStore.increment() counterStore.incrementNum(10) }</script>6.3 Actions中的异步操作import { defineStore } from 'pinia'const useHome = defineStore("home", { state: () => ({ banners: [], recommends: [] }), actions: { async fetchHomeMultidata() { const res = await fetch("http://123.207.32.32:8000/home/multidata") const data = await res.json() //得到数据后直接复制给state this.banners = data.data.banner.list this.recommends = data.data.recommend.list return 'success' } }})export default useHome6.4 调用异步actions方法<script setup> import useHome from '@/stores/home'; const homeStore = useHome() homeStore.fetchHomeMultidata().then(res => { console.log("fetchHomeMultidata的action已经完成了:", res) })</script>
本文链接地址:https://www.jiuchutong.com/zhishi/293147.html 转载请保留说明!

上一篇:(HOTA)多目标跟踪MOT指标计算方法(多目标pso)

下一篇:尚融宝28-投资列表展示(尚融宝盈(宁波)投资中心(有限合伙))

  • 减免税款的会计分录在什么时候处理
  • 安装服务费增值税专票税率多少
  • 事业单位资产负责比往年增加表明什么
  • 固定资产分期付款会计处理
  • 房地产公司资本公积
  • 银行打出的明细清单怎么看不懂
  • 前期差错会计处理知乎
  • 企业税收滞纳金需要纳税调整吗
  • 优惠券抵扣账务处理流程
  • 房地产公司扣减土地出让金怎么入账?
  • 所得税汇算清缴账务处理
  • 可供出售金融资产包括哪些内容
  • 盘亏设备一台
  • 企业没有收入怎么办
  • 企业的完工产品是指
  • 企业接受固定资产投资
  • 采购合同含税未税合同模板
  • 7月1日所有公司发票系统需要升级,办公用品发票买什么开什么
  • 员工服装属于什么费用类型
  • 资产处置损失计算方法
  • 投资其他公司的钱计入什么科目
  • 小规模纳税人月销售额不超过10万免征
  • 以前年度损益调整借贷方向
  • 应收出口退税属于哪个会计科目
  • 在建工程预估转入固定资产怎么做凭证
  • macos10.10.5怎么升级
  • bios密码忘记了怎么清除,放电不行
  • 销售折扣收货方法有哪些
  • 冷车启动缺缸热车正常已解决
  • 借条和欠条的区别 法律效力
  • 为什么linux这么受欢迎
  • 莱奇沃思田园城市
  • 行政事业性收费目录
  • svg图形是什么
  • 空调维修费进什么会计科目
  • php读取word内容
  • 税务局清税
  • 应收利息的会计处理方法
  • 做工程没钱了可以贷款吗
  • 施工企业的人工费占比
  • python concat函数用法
  • 商业汇票利息账务处理如何做?
  • 工会经费的会计分录2022
  • 开具红字增值税专用发票信息表在哪
  • sqlserver存储过程在哪里
  • 防伪码显示查询次数和时间
  • 现金存货盘盈盘亏计入什么科目
  • 固定资产转移说明模板
  • 运费发票如何做分录
  • 捐赠支出税前扣除标准
  • 增值税专用设备是什么
  • 新会计制度固定资产折旧账务处理
  • 企业领用产品的会计分录
  • 银行公司账户限额
  • 营改增之后账务怎么处理
  • 什么叫系统服务
  • 赠送给客户的商品怎么做会计分录
  • mysqldump命令在哪里执行
  • VMWare linux mysql 5.7.13安装配置教程
  • 在centOS 7安装mysql 5.7的详细教程
  • 注册表 启动
  • win8蓝屏代码大全
  • 通过修改注册表来修改chrome配置
  • 在xp系统中设置u盘启动
  • 桌面上家庭组图标是干嘛
  • linux jre
  • 进程管理器命令
  • win7 android studio
  • shell脚本for循环 计算1到100的和
  • jquery滚动到底部
  • unity3d c++开发
  • three.js typescript
  • 你应该知道的几个问题
  • jquery遍历object
  • javascript学习指南
  • 税务疑点核查报告
  • 1+征收率
  • 北京摇号摇中了能过户吗
  • 扬州税务学院住宿环境
  • 杭州文明城市几连冠
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设