Pinia库的使用及问题分析
Pinia 是一个用于 Vue 的状态管理库,类似 Vuex, 是 Vue 的另一种状态管理方案
Pinia 支持 Vue2 和 Vue3 引用尤雨溪的话:pinia会替代vuex吗
很大概率,都是core team成员,讨论结果未来形态会很像pinia,新东西都写在pinia里,如果开发一个新项目,如果使用ts,推荐使用pinia。
官网链接: 官方文档
Github链接 : GithubPinia和Vuex比的优势符合直觉,易于学习 极轻, 仅有 1 KB 模块化设计,便于拆分状态 Pinia 可以自由扩展 官方文档 PluginsPinia的使用安装Pinia# 使用 npm npm install pinia@next // v2:应用于vue3中 npm install pinia@latest // v1: 应用于v2中 # 使用 yarn yarn add pinia@next
提示:pinia@next安装将会安装v2的版本,如果你想要在vue2中使用,需要安装v1:pinia@latest 和 @vue/composition-api. 这里不做介绍了。
创建一个pinia(根储存)并挂载到app上 // vue3中 import { createPinia } from "pinia" app.use(createPinia()) // vue2中 import { createPinia, PiniaPlugin } from "pinia" Vue.use(PiniaPlugin) const pinia = createPinia() new Vue({ el: "#app", // other options... // ... // note the same `pinia` instance can be used across multiple Vue apps on // the same page pinia, })如何定义一个store?
pinia通过使用一个方法defineStore() 来定义store,但是要注意的,store必须要有唯一的名字。import { defineStore } from "pinia" // useStore could be anything like useUser, useCart // the first argument is a unique id of the store across your application export const useStore = defineStore("main", { // other options... }) // 或者 export const useStore = defineStore({ // id: 必须的,在所有 Store 中唯一 id: "main", // 其他配置 })使用store// demo.vue {{store.count}} State
最简单的使用方式stateconst store = useStore() store.counter++ // 重置state const store = useStore() store.$reset()
同vuex一样,在使用的时候也可以直接使用mapState遍历state属性(只读)import { mapState } from "pinia" export default { computed: { // gives access to this.counter inside the component // same as reading from store.counter ...mapState(useStore, ["counter"]) // same as above but registers it as this.myOwnName ...mapState(useStore, { myOwnName: "counter", // you can also write a function that gets access to the store double: store => store.counter * 2, // it can have access to `this` but it won"t be typed correctly... magicValue(store) { return store.someGetter + this.counter + this.double }, }), }, }
通过mapWritableState() 函数可以对state进行修改import { mapWritableState } from "pinia" export default { computed: { // gives access to this.counter inside the component and allows setting it // this.counter++ // same as reading from store.counter ...mapWritableState(useStore, ["counter"]) // same as above but registers it as this.myOwnName ...mapWritableState(useStore, { myOwnName: "counter", }), }, }
这里注意这个方法对数组元素不生效,官网说明如下图:
使用$patch 可以进行state值的更新,并且支持多个值同时操作。store.$patch({ counter: store.counter + 1, name: "Abalam", })
通过$subscribe() 完成对值变化的监听。cartStore.$subscribe((mutation, state) => { // import { MutationType } from "pinia" mutation.type // "direct" | "patch object" | "patch function" // same as cartStore.$id mutation.storeId // "cart" // only available with mutation.type === "patch object" mutation.payload // patch object passed to cartStore.$patch() // persist the whole state to the local storage whenever it changes localStorage.setItem("cart", JSON.stringify(state)) })
通过localStorage还可以对值进行一个储存,避免被刷新。
对整个pinia state进行监听的话,使用如下:watch( pinia.state, (state) => { // persist the whole state to the local storage whenever it changes localStorage.setItem("piniaState", JSON.stringify(state)) }, { deep: true } )Getters
Pinia 中的 Getters 作用与 Vuex 中的 Getters 相同,但使用略有差异。
Pinia 中的 Getters 直接在 Store 上读取,形似 Store.xx,就和一般的属性读取一样。 Getters的基本使用
Getter 第一个参数是 state,是当前的状态,也可以使用 this.xx 获取状态。
Getter 中也可以访问其他的 Getter, 或者是其他的 Store。
例子: // 修改 store.js import { defineStore } from "pinia"; import { otherState } from "@/store/otherState.js"; export const useStore = defineStore({ id: "myGlobalState", state: ()=> ({ count: 2 }), getters: { // 一个基本的 Getter: 计算 count 的平方 // 使用参数 countPow2(state) { return state.count ** 2; }, // 使用 this /* countPow2() { return this.count ** 2; }, */ // 简单的 Getter 直接使用箭头函数 // countPow2: state=> state.count ** 2 // 获取其它 Getter, 直接通过 this countPow2Getter() { return this.countPow2; } // 使用其它 Store otherStoreCount(state) { // 这里是其他的 Store,调用获取 Store,就和在 setup 中一样 const otherStore = useOtherStore(); return state.count; }, } }); // otherState.js import { defineStore } from "pinia"; export const useStore = defineStore({ id: "otherState", state: ()=> ({ count: 5 }), });actions
Pinia 没有 Mutations ,统一在 actions 中操作 state,通过this.xx 访问相应状态
虽然可以直接操作 Store,但还是推荐在 actions 中操作,保证状态不被意外改变
action 和普通的函数一样
action 同样可以像 Getter 一样访问其他的 Store,同上方式使用其它 Store // store.js export const useStore({ state: ()=> ({ count: 2, // ... }) // ... actinos: { countPlusOne() { this.count++; }, countPlus(num) { this.count += num; } } })如何实现一个?
针对这个pinia的使用,前面讲了这么多api的使用,这些也都是在官网中有介绍的,下面在项目中实际来用下这个库
遇到的问题使用前必须要先注册@vue/composition-api,不然在vue2中不能使用import VueCompositionAPI from "@vue/composition-api"; import { createPinia } from "pinia"; Vue.use(VueCompositionAPI); // 这里注意:使用之前必选要先注册VueCompositionAPI const pinia = createPinia();
国庆不知道去哪里玩?看完这篇你就知道了北方最美的自驾公路,中国66号公路,张家口的草原天路!张家口张北县的草原天路,被誉为中国最美公路之称的自驾宝地。天蓝草绿云白都是它的代言词,大家可能很好奇,一个公路能有多美呢?那是
秋天燥气大,咽喉干燥疼痛咳嗽痰少的可以用此方润肺好文分享随食养秋天最大的特点就是干燥,这不,早上刚起床洗完脸,就觉得自己的脸火辣辣的,对着镜子一看,天哪,居然有点掉皮脱屑。这是由于秋天燥气太大,导致皮肤里面的水分严重不足,于是皮
秋季不养,一年白忙,建议多吃秋天6宝,健康安稳度秋人一旦到了中年,饮食习惯不得不注意,既要注重营养均衡,又不能吃得油腻辛辣。中老年人做到健康饮食,要吃得全面,吃得营养吃得对胃口,别不舍得吃不舍得花钱,有个健康的身体比什么都好。强烈
秋吃酸,护肝胆,建议秋天常吃这5酸,不仅润肺还保肝俗话说秋吃酸,护肝胆。意思就是说在秋天的时候最好多吃一些酸性的食物。因为酸性的食物容易到达肝脏部位从而起到调节作用,今天给大家分享秋天,建议常吃这5酸不仅润肺还保肝。一牛肉推荐食谱
高铁30分钟直达!弥勒这个小镇,藏着秋天里你向往的生活来源云南日报浪漫初秋去哪玩?不妨来弥勒从昆明南站坐高铁出发半小时即可到达弥勒来到弥勒一定不能错过太平湖森林小镇因为这里藏着初秋里你向往的生活从太平湖森林小镇这个名字可以看出,小镇被
石家庄森林河趣那花园,温馨浪漫,充满童趣,是假日休闲的好去处又到了秋高气爽的好时节。石家庄周边看秋景的地方不少,如果不想走太远,位于滹沱河畔的森林河趣那花园是个不错的选择。这里或许有石家庄最大的薰衣草庄园。走入其中,大片薰衣草在眼前铺陈开来
最近突然火了一种裤子电工裤,百搭又时髦显瘦,太适合秋天了对于今天的Z世代来说,我们已经看到了一种强烈的怀旧感,她们的衣橱里面到处都是1990年代和2000年代的主题。这是趋势分析师GeraldineWharry所说的话语,从侧面表达出复
思维认知一个有内涵的人是因为他认清了这两点人与人之间为何差异如此之大?为何有些人书没读多少,人际关系游刃有余,为何有些人饱读诗书社会行走却寸步难行?在这个看脸的时代,长相不好就注定没有前途?长相好看的就一定会获得认同和成功
分享郑风风雨人间皆值得总有那么一个人,即使你被世人遗忘,他也会不离不弃,寻遍天下,只为与你同醉江湖。总有那么一个人,会懂得你的一切。风雨凄凄,鸡鸣喈喈。既见君子,云胡不夷。风雨潇潇,鸡鸣胶胶。既见君子,
过好今生今世,莫管前生后世我是不信神的,是无神论者。不管别人信不信,信仰自由。可能有神也有鬼,但我没见过,所以不信。要说有鬼,我见过的鬼,不知是真是假,那就是牛鬼蛇神,文化大革命时见得多了。可能我们的亲人就
再一次想你再一次想你刘卫玲生活总在变换选择便只能乐意孤身穿行在茫茫人海让涌动的激越故事覆盖不如愿的冷焰复燃期约的晨曦直入浅浅的怀念站在离你不远不近的咫尺再一次知道我不是炭火无法为你自立的日子