位置: 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-投资列表展示(尚融宝盈(宁波)投资中心(有限合伙))

  • 小微企业应纳税所得额是指什么
  • 什么合同属于有效合同
  • 购买财务软件可以抵税吗
  • 建筑公司劳务分包抵扣分录
  • 小规模纳税人注册资金最高多少
  • 承兑汇票大回头票是什么意思
  • 分期收款怎么做账
  • 申报怎么打印
  • 固定资产的折旧费用计入什么科目
  • 有限合伙企业合伙人责任
  • 定额备用金制度有哪些
  • 转账显示未认证
  • 免抵退税额账务处理流程
  • 已确认并转销的应收账款会计分录
  • 房屋租赁发票能抵扣几个点
  • 以现金形式发放的员工餐费补贴,可并入职工福利费
  • 资产负债表其他应付款包括哪些
  • 小规模纳税人销售农产品免税吗
  • 小规模纳税人增值税优惠政策2023
  • 本金和利息分别出具借条
  • 以前年度少计收入 会计怎么处理
  • 预存话费返还怎么操作
  • 资产处置损失减少的原因
  • 评估的房产如何入账
  • 一键ghost有用吗
  • 没收到电费账单怎么办
  • 收到客户付款 会计分录
  • 什么是摊余成本计量的金融资产
  • extract php函数
  • 认缴制注册资金不交可以吗
  • element动态变化表格列
  • 时序21-21-21-47
  • 固定资产闲置能报废吗
  • linux rm 命令
  • 税款入库期是什么意思
  • python爬虫中数据接口的含义
  • 长期应收款如何核算
  • 税控服务费电子普票能抵扣吗
  • 为客户购买的机票怎么入账
  • 长期股权投资实现的净利润权益法
  • 资产负债表和利润表的区别
  • 招待费专票不可以抵扣
  • 核定征收和查账征收可以自己选择吗
  • 饭店开业多久可以正常
  • 购进国内交通运输产品
  • 无法收回的应收账款可以税前扣除吗
  • 平销返利是销售折扣吗
  • 股权转让会计账务处理方法
  • 从工程款中扣除质保金
  • 冲销应付账款暂估应付账款的分录怎么做
  • 公司向员工个人借款怎么处理
  • mysql双主复制
  • 什么是格式良好的xml文档
  • win8.1 multiple edition
  • ubuntu开启图形化界面
  • linux 解析
  • centos怎么扩容
  • win10系统中怎么打开IE浏览器
  • xp系统explorer.exe错误
  • centos中如何安装软件
  • win10如何禁用windows defender
  • windows10粘滞键
  • 鼠标双击速度
  • centos6.9
  • surface使用
  • opengl 4.X off-screen rendering
  • 第一个闹钟
  • perl如何使用
  • ftp下载工具能自动登录ftp服务器
  • js网页自动化
  • convert fs
  • javascript SpiderMonkey中的函数序列化如何进行
  • 要使物体从静止状态转变为运动状态需要对这个物体什么
  • 湖北农信换手机登录不了
  • 建筑工程提前投入使用
  • 广东省电子税务局app下载官网
  • 360浏览器hi真不巧
  • 青椒课堂怎么激活登录
  • 中介服务行业
  • 海关退税是什么意思啊
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

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

    友情链接: 武汉网站建设