Pinia 是什么?
Pinia 是一个用于 Vue 的状态治理库,相似 Vuex, 是 Vue 的另一种状态治理计划
Pinia 反对 Vue2 和 Vue3
本文只讲 Pinia 在 Vue3 中的应用, 在 Vue2 中应用略有差别,参考 官网文档
Pinia 劣势
合乎直觉,易于学习
极轻, 仅有 1 KB
模块化设计,便于拆分状态
装置 Pinia
装置须要 @next 因为 Pinia 2 处于 beta 阶段, Pinia 2 是对应 Vue3 的版本
# 应用 npmnpm install pinia@next# 应用 yarnyarn add pinia@next
创立一个 pinia(根存储)并将其传递给应用程序:
import { createPinia } from 'pinia';app.use(createPinia());
外围概念与根本应用
Store
Store 是一个保留状态和业务逻辑的实体,能够自在读取和写入,并通过导入后在 setup 中应用
创立一个 store
// store.jsimport { createStore } from "pinia";// createStore 调用后返回一个函数,调用该函数取得 Store 实体export const useStore = creteStore({ // id: 必须的,在所有 Store 中惟一 id: "myGlobalState", // state: 返回对象的函数 state: ()=> ({ count: 1 }),});
应用 Store
// xxx.vue<template> <div> {{store.count}} </div></template><script> // 导入 Store, 应用本人的门路 import { useStore } from "@/store/store.js"; export default { setup() { // 调用函数 取得Store const store = useStore(); return { store } } }</script>
Getters
Pinia 中的 Getters 作用与 Vuex 中的 Getters 雷同,但应用略有差别
Pinia 中的 Getters 间接在 Store 上读取,形似 Store.xx,就和个别的属性读取一样
Getter根本应用
Getter 第一个参数是 state,是以后的状态,也能够应用 this.xx 获取状态
Getter 中也能够拜访其余的 Getter, 或者是其余的 Store
例子:
// 批改 store.jsimport { createStore } from "pinia";import { otherState } from "@/store/otherState.js";export const useStore = creteStore({ 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.jsimport { createStore } from "pinia";export const useStore = creteStore({ id: "otherState", state: ()=> ({ count: 5 }),});
actions
Pinia 没有 Mutations,对立在 actions 中操作 state,通过this.xx 拜访相应状态
尽管能够间接操作 Store,但还是举荐在 actions 中操作,保障状态不被意外扭转
action 和一般的函数一样
action 同样能够像 Getter 一样拜访其余的 Store,同上形式应用其它 Store,这里不在赘述,具体请移步 官网文档 Actions
action 根本应用
// store.jsexport const useStore({ state: ()=> ({ count: 2, // ... }) // ... actinos: { countPlusOne() { this.count++; }, countPlus(num) { this.count += num; } }})
总结
Pinia 相比 Vuex 更加简略,而且 Pinia 能够自在扩大 官网文档 Plugins
Pinia 是合乎直觉的状态治理形式,让使用者回到了模块导入导出的原始状态,使状态的起源更加清晰可见
Pinia 的应用感触相似于 Recoil,但没有那么多的概念和 API,主体十分精简,极易上手(Recoil 是 Facebook 官网出品的用于 React 状态治理库,应用 React Hooks 治理状态)
Pinia 2 目前还在 Beta 状态,不倡议在生产环境中应用,不过置信稳固了当前会成为 Vue 生态中另一大状态治理计划