vue中状态管理器Pinia的用法详解

 更新时间:2023年10月20日 14:36:45   作者:yuobey  
Pinia 是 Vue.js 的轻量级状态管理库,最近很受欢迎,它使用 Vue 3 中的新反应系统来构建一个直观且完全类型化的状态管理库,下面就跟随小编一起来学习一下它的具体使用吧

一、pinia介绍

Pinia 是 Vue.js 的轻量级状态管理库,最近很受欢迎。它使用 Vue 3 中的新反应系统来构建一个直观且完全类型化的状态管理库。

Pinia的成功可以归功于其管理存储数据的独特功能(可扩展性、存储模块组织、状态变化分组、多存储创建等)。

pinia优点:

  • 符合直觉,易于学习
  • 极轻, 仅有 1 KB
  • 模块化设计,便于拆分状态
  • Pinia 没有 mutations,统一在 actions 中操作 state,通过this.xx 访问相应状态虽然可以直接操作 Store,但还是推荐在 actions 中操作,保证状态不被意外改变
  • store 的 action 被调度为常规的函数调用,而不是使用 dispatch 方法或 MapAction 辅助函数,这在 Vuex 中很常见
  • 支持多个Store
  • 支持 Vue devtools、SSR 和 webpack 代码拆分

pinia缺点:

不支持时间旅行和编辑等调试功能

二、安装使用Pinia

在项目根目录中打开终端,输入以下命令

yarn add pinia@next 
# or with npm 
npm install pinia@next
// 该版本与Vue 3兼容,如果你正在寻找与Vue 2.x兼容的版本,请查看v1分支。

直接在main.js中使用

import { createApp } from "vue";
import App from "./App.vue";
import { setupStore } from "./store/index"; //引入pinia 缓存实例
const app = createApp(App);
setupStore(app); //把创建出来的vue实例app 传入setupStore函数 进行挂载
app.mount("#app");

创建store文件夹,一般的项目我们可以不区分模块,但是按照习惯,个人觉得区分模块会让代码阅读起来更加清晰

如:

store/index.js

import { createPinia } from "pinia";
const store = createPinia();
export function setupStore(app) {
    app.use(store);
}
export { store };

创建模块app.js代码:

import { defineStore } from "pinia";
export const useAppStore = defineStore({
  // id is required so that Pinia can connect the store to the devtools
  id: "app",
  state: () => ({
    clientWidth: "",
    clientHeight: ""
  }),
  getters: {
    getClientWidth() {
      return this.clientWidth;
    },
    getClientHeight() {
      return this.clientHeight;
    }
  },
  actions: {
    setClientWidth(payload) {
      try {
        setTimeout(() => {
          this.clientWidth = payload;
        }, 2000);
      } catch (error) {}
    },
    setClientHeight(payload) {
      try {
        setTimeout(() => {
          this.clientHeight = payload;
        }, 2000);
      } catch (error) {}
    }
  }
});

使用其实很简单,只要在对应组件引入对应的模块

如:

<template>
  {{ width }}
</template>

<script>
import { ref, reactive, onMounted,computed } from "vue";
import { useAppStore } from "@/store/modules/app";

export default {
  name: "App",
  setup() {
    const appStore = useAppStore();
    const width = computed(() => {
      return appStore.clientWidth;
    });
    onMounted(() => {
      appStore.setClientWidth(200);
    });
    return {
      width,
    };
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

pinia还可以在当前模块很直观的使用其他模块的方法

如:

import { defineStore } from "pinia";
import { useOtherStore } from "@/store/modules/other.js";
export const useAppStore = defineStore({
  // id is required so that Pinia can connect the store to the devtools
  id: "app",
  //state必须是一个返回对象的函数
  state: () => ({
    clientWidth: "",
    clientHeight: ""
  }),
  getters: {
    getClientWidth() {
      return this.clientWidth;
    },
    getClientHeight() {
      return this.clientHeight;
    },
       // 使用其它 Store
    otherStoreCount(state) {
      // 这里是其他的 Store,调用获取 Store,就和在 setup 中一样
      const otherStore = useOtherStore();
      return otherStore.count;
    },
  },
  actions: {
    setClientWidth(payload) {
      try {
        setTimeout(() => {
          this.clientWidth = payload;
        }, 2000);
      } catch (error) {}
    },
    setClientHeight(payload) {
      try {
        setTimeout(() => {
          this.clientHeight = payload;
        }, 2000);
      } catch (error) {}
    },
    // 使用其它模块的action
    setOtherStoreCount(state) {
      // 这里是其他的 Store,调用获取 Store,就和在 setup 中一样
      const otherStore = useOtherStore();
         otherStore.setMethod()
    },
  }
});

三、Pinia 中Actions改变state的几种方法

我们在组件中,引入对应模块后如:

<template>
  {{ width }}
</template>

<script>
import { ref, reactive, onMounted,computed } from "vue";
import { useAppStore } from "@/store/modules/app";

export default {
  name: "App",
  setup() {
    const appStore = useAppStore();
    const width = computed(() => {
      return appStore.clientWidth;
    });
    onMounted(() => {
      appStore.setClientWidth(200);
    });
    //演示三种方法修改state
    const changeAppstoreStateClick = () => {
     // 方式一:直接修改 -> 'direct'
      appStore.clientWidth += 400;
     // 方式二:patch对象方式 -> 'patch object',调用$patch 传入要修改的键和val
      appStore.$patch({
        clientWidth: appStore.clientWidth + 400,
      });
      // 方式三:patch函数方式 -> 'patch function',可键入语句,执行复杂逻辑
      appStore.$patch((state) => {
        state.clientWidth += 400;
      });

    };
    return {
      width,
      changeAppstoreStateClick
    };
  },
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

以上就是vue中状态管理器Pinia的用法详解的详细内容,更多关于vue状态管理器Pinia的资料请关注脚本之家其它相关文章!

相关文章

  • webpack 3 + Vue2 使用dotenv配置多环境的步骤

    webpack 3 + Vue2 使用dotenv配置多环境的步骤

    这篇文章主要介绍了webpack 3 + Vue2 使用dotenv配置多环境,env文件在配置文件都可以用, vue页面用的时候需要在 webpack.base.conf.js 重新配置,需要的朋友可以参考下
    2023-11-11
  • vue多页面开发和打包正确处理方法

    vue多页面开发和打包正确处理方法

    这篇文章主要介绍了vue多页面开发和打包的正确处理方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下
    2018-04-04
  • vue+element创建动态的form表单及动态生成表格的行和列

    vue+element创建动态的form表单及动态生成表格的行和列

    这篇文章主要介绍了vue+element创建动态的form表单及动态生成表格的行和列 ,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-05-05
  • vue同一浏览器登录多账号处理方案

    vue同一浏览器登录多账号处理方案

    项目在线上会遇到管理员类似权限比较大的用户,会在同一浏览器登陆多个账号,遇到这样的问题如何处理呢,下面小编给大家介绍vue同一浏览器登录多账号处理方法,感兴趣的朋友一起看看吧
    2024-01-01
  • Vue前端导出页面为PDF文件的最佳方案

    Vue前端导出页面为PDF文件的最佳方案

    这篇文章主要介绍了前端导出PDF方案,通过html2canvas和jsPDF实现单页导出,利用iframe分批处理列表页数据并打包ZIP,兼顾性能与样式还原,有效减轻服务端压力,需要的朋友可以参考下
    2025-07-07
  • vue3+uniapp 上传附件的操作代码

    vue3+uniapp 上传附件的操作代码

    uni-file-picker搭配uni.uploadFile在使用问题上踩了不少坑,我至今还是没办法在不改uniapp源码基础上实现限制重复文件的上传,这篇文章介绍vue3+uniapp 上传附件的操作代码,感兴趣的朋友一起看看吧
    2024-01-01
  • 使用Vue3和Vite实现对低版本浏览器的兼容

    使用Vue3和Vite实现对低版本浏览器的兼容

    在使用Vite和Vue3构建的JavaScript项目中,确保对低版本浏览器的兼容性是一个重要的考虑因素,以下是一些具体的解决方案和步骤,可以帮助你实现这一目标,需要的朋友可以参考下
    2024-11-11
  • 前端小技能之Vue集成百度离线地图功能总结

    前端小技能之Vue集成百度离线地图功能总结

    最近项目里集成了百度地图的一些功能,所以下面这篇文章主要给大家介绍了关于前端小技能之Vue集成百度离线地图功能的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2023-01-01
  • vue3数据监听watch/watchEffect的示例代码

    vue3数据监听watch/watchEffect的示例代码

    我们都知道监听器的作用是在每次响应式状态发生变化时触发,在组合式 API 中,我们可以使用 watch()函数和watchEffect()函数,下面我们来看下vue3如何进行数据监听watch/watchEffect,感兴趣的朋友一起看看吧
    2023-02-02
  • 基于better-scroll 实现歌词联动功能的代码

    基于better-scroll 实现歌词联动功能的代码

    BetterScroll 是一款重点解决移动端(已支持 PC)各种滚动场景需求的插件,BetterScroll 是使用纯 JavaScript 实现的,这意味着它是无依赖的。本文基于better-scroll 实现歌词联动功能,感兴趣的朋友跟随小编一起看看吧
    2020-05-05

最新评论