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的资料请关注脚本之家其它相关文章!

相关文章

  • Vue-cli3项目配置Vue.config.js实战记录

    Vue-cli3项目配置Vue.config.js实战记录

    这篇文章主要给大家介绍了关于Vue-cli3项目配置Vue.config.js的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-07-07
  • vue watch内部调用methods方法报错的解决方案

    vue watch内部调用methods方法报错的解决方案

    这篇文章主要介绍了vue watch内部调用methods方法报错的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-04-04
  • vue 自定义组件的写法与用法详解

    vue 自定义组件的写法与用法详解

    这篇文章主要介绍了vue 自定义组件的写法与用法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值 ,需要的朋友可以参考下
    2020-03-03
  • Vue-CLI3.x 设置反向代理的方法

    Vue-CLI3.x 设置反向代理的方法

    这篇文章主要介绍了Vue-CLI3.x 设置反向代理的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-12-12
  • 基于Vue 实现一个中规中矩loading组件

    基于Vue 实现一个中规中矩loading组件

    这篇文章主要介绍了基于Vue 实现一个中规中矩loading组件,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-04-04
  • vue实现高德地图添加多个点标记

    vue实现高德地图添加多个点标记

    地图多点标注其实是个非常简单的问题,这篇文章主要给大家介绍了关于vue实现高德地图添加多个点标记的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2023-06-06
  • 详解Vue3中Watch监听事件的使用

    详解Vue3中Watch监听事件的使用

    这篇文章主要为大家详细介绍了Vue3中Watch监听事件的使用的相关资料,文中的示例代码讲解详细,对我们学习Vue3有一定的帮助,需要的可以参考一下
    2023-02-02
  • VUE v-bind 数据绑定的示例详解

    VUE v-bind 数据绑定的示例详解

    这篇文章主要介绍了VUE v-bind 数据绑定,简单点来说就是对 HTML 中的元素,我们可以使用 v-bind 来进行绑定和动态的数据输出,本文结合示例代码给大家介绍的非常详细,需要的朋友可以参考下
    2023-05-05
  • vue中vue-router的使用说明(包括在ssr中的使用)

    vue中vue-router的使用说明(包括在ssr中的使用)

    这篇文章主要介绍了vue中vue-router的使用说明(包括在ssr中的使用),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-05-05
  • Vue下拉框加分页搜索功能的实现方法

    Vue下拉框加分页搜索功能的实现方法

    开发任务中有这样一个需求,下拉框中需要展示超过5000条数据,甚至更多,这数据量直接整个页面卡死了,就想到在下拉框中加分页,下面小编通过实例代码介绍下Vue下拉框加分页搜索功能的实现,感兴趣的朋友一起看看吧
    2022-11-11

最新评论