Pinia 基本使用

Pinia 中文文档:pinia.web3doc.top/

Pinia 的介绍

Pinia 最初是为了探索 Vuex 下一次迭代而产生的,结合了 Vue5 核心团队的很多想法。最终团队意识到 Pinia 已经实现了 Vue5 的大部分内容,决定实验 Pinia 来替代 Vuex。

Pinia 与 Vuex 的对比

  • mutations 不在存在。
  • Pinia 与 Vuex 的对比,Pinia 提供了更简单的 api,并且与 ts 一起使用时具有更可靠的类型判断。
  • 没有模块嵌套和命名空间,不在需要记住他们之间的关系。

安装 Pinia

plaintext 复制代码
yarn add pinia
# 或者使用 npm
npm install pinia

定义 Store

this 可以访问到 整个 store 的实例

plaintext 复制代码
import { defineStore } from 'pinia'

// useStore 可以是 useUser、useCart 之类的任何东西
// 第一个参数是应用程序中 store 的唯一 id,官方的约束是use***,以use+name的一个约定,不是必须,只是建议
export const useStore = defineStore('main', {
 state: () => { // 数据
    return {
      // 所有这些属性都将自动推断其类型
      counter: 0,
      name: 'Eduardo',
      isAdmin: true,
    }
  },
 getters: { // 同计算属性
    doubleCount: (state) => state.counter * 2,
  },
 actions: {
    increment() {
      this.counter++
    },
    randomizeCounter() {
      this.counter = Math.round(100 * Math.random())
    },
  },
})

修改 Store 的数据

注意:修改的数据如果直接结构,数据不是响应式的

使用 Vue 的 toRefs()或 Pinia 的 storeToRefs()

  1. 在组件中引入 Store 直接修改

    js 复制代码
    // 简单粗暴
    import {Store} from '../store/index'
    const store = Store()
    const handleClick = () => {
    	store.count++
    }
  2. 使用$patch 对象

    js 复制代码
    // 多数据修改做过优化
    import {Store} from '../store/index'
    const store = Store()
    const handleClick = () => {
    	store.$patch({
    		count:store.count+2
    	})
    }
  3. 使用$patch 函数

    js 复制代码
    // 使用的是函数,可以处理复制的业务
    import {Store} from '../store/index'
    const store = Store()
    const handleClick = () => {
    	store.$patch((state)=>{
    		state.count++
    	})
    }
  4. 在 actions 中修改

    js 复制代码
    // 用于复杂或多处使用相同的方法
    actions: {
        changeState(){
            this.count++
        }
    }
    // 在组件中使用
    store.changeState()

Pinia 中的 getters 使用

与 Vue 的计算属性一样,修改的数据有缓存,对性能优化有好处

js 复制代码
getters: { // 同计算属性
	doubleCount: (state) => state.counter * 2,
	phoneHidden: (state) => state.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/,'$1****$2')
}
// 组件中使用
store.doubleCount

Pinia 中 Store 的互相调用

不同的 Store 的相互调用非常简单,和组件使用相同

js 复制代码
import {userInfo} from '../store/userInfo'
const store = userInfo()
store.xxx
需要在哪使用直接拿即可

Pinia 组合式

上面的使用方法更适合 Vue2 的形式,在 Vue3 中更使用组合式

将 defineStore 的第二个参数改为函数,需要使用的值返回出去

typescript 复制代码
import { defineStore } from "pinia";
import { ref } from "vue";

// 定义 Store,使用函数,更适合Vue3,注意要使用ref并将需要的数据或函数返回出去
export const useTestStore = defineStore(
  "test",
  () => {
    // 定义的变量使用ref
    const testText = ref<string>("");

    // 保存会员信息,登录时使用
    const setTestText = (val: string) => {
      testText.value = val;
    };

    // 清理会员信息,退出时使用
    const clearsetTestText = () => {
      testText.value = "";
    };

    // 返回需要使用的变量,和setup函数一样
    return {
      testText,
      setTestText,
      clearsetTestText,
    };
  }
);

持久化

pinia 的数据默认情况下刷新后会丢失

pinia-plugin-persistedstate:帮助 pinia 持久化的插件

uniapp 的代码示例:

typescript 复制代码
// index.ts
import { createPinia } from "pinia";
import persist from "pinia-plugin-persistedstate";

// 创建 pinia 实例
const pinia = createPinia();
// 使用持久化存储插件
pinia.use(persist);

// 默认导出,给 main.ts 使用
export default pinia;

// 统一导出
export * from "./modules/test";
typescript 复制代码
// modules/test.ts
import { defineStore } from "pinia";
import { ref } from "vue";
// 实际上可以直接使用 uni.getStorageSync() ,但是使用原生的方式理论上性能会好一点(不需要经过uniapp的编译/处理)
let persist;
// #ifdef H5 || WEB
persist = true;
// #endif
// #ifndef H5 || WEB
persist = {
  storage: {
    getItem(key: string) {
      return uni.getStorageSync(key);
    },
    setItem(key: string, value: any) {
      uni.setStorageSync(key, value);
    },
  },
};
// #endif

// 定义 Store,使用函数,更适合Vue3,注意要使用ref并将需要的数据或函数返回出去
export const useTestStore = defineStore(
  "test",
  () => {
    const testText = ref<string>("");

    // 保存会员信息,登录时使用
    const setTestText = (val: string) => {
      testText.value = val;
    };

    // 清理会员信息,退出时使用
    c
相关推荐
多则惑少则明1 小时前
Vue开发系列——自定义组件开发
前端·javascript·vue.js
羽沢312 小时前
Vue3组件间通信——pinia
前端·javascript·vue.js
hxmmm4 小时前
vue多页项目如何在每次版本更新时做提示
vue.js·vue-router
一 乐4 小时前
二手车销售|汽车销售|基于SprinBoot+vue的二手车交易系统(源码+数据库+文档)
java·前端·数据库·vue.js·后端·汽车
Sheldon一蓑烟雨任平生4 小时前
Vue 用户管理系统(路由相关练习)
vue.js·vue3·axios·json-server·vue-router·vue 路由·vue-link
李剑一5 小时前
前端实现时间轴组件拼接N多个不连续监控视频展示
前端·vue.js
@大迁世界5 小时前
第06章:Dynamic Components(动态组件)
前端·javascript·vue.js·前端框架·ecmascript
Revol_C6 小时前
【Element Plus】升级版本后,el-drawer自定义的关闭按钮离奇消失之谜
前端·css·vue.js
caicai_lf_niuniu6 小时前
🌳 ComboTreeV2:高性能虚拟树
前端·vue.js
梵得儿SHI7 小时前
Vue 核心语法详解:模板语法中的绑定表达式与过滤器(附 Vue3 替代方案)
前端·javascript·vue.js·插值语法·vue模板语法·绑定表达式·过滤器机制