前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >vue3了,试试轻量化的Vuex -- Pinia?

vue3了,试试轻量化的Vuex -- Pinia?

作者头像
玖柒的小窝
修改2021-11-04 09:25:37
1.5K0
修改2021-11-04 09:25:37
举报
文章被收录于专栏:各类技术文章~
vue3了,试试轻量化的Vuex -- Pinia?
vue3了,试试轻量化的Vuex -- Pinia?

vue3了,试试轻量化的Vuex -- Pinia?

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

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

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

直接在main.js中使用

代码语言:javascript
复制
import { createApp } from "vue";
import App from "./App.vue";

createApp(App).use(createPinia()).mount("#app");
复制代码

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

如:

创建模块app.js代码:

代码语言:javascript
复制
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) {}
    }
  }
});
复制代码

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

如:

代码语言:javascript
复制
<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还可以在当前模块很直观的使用其他模块的方法

如:

代码语言:javascript
复制
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的几种方法

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

代码语言:javascript
复制
<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>

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • vue3了,试试轻量化的Vuex -- Pinia?
    • 一, pinia介绍
      • 二,安装使用Pinia
        • 三, Pinia 中Actions改变state的几种方法
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档