试试轻量化的Vuex -- Pinia

6,724 阅读2分钟

一, 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>