类Vuex轻量级状态管理实现

引用自 摸鱼wiki

1. vuex

vuex是一个前端广泛流行的状态管理库,主要由以下几大模块组成:

  1. state:状态存储
  2. getter:属性访问器
  3. mutation:可以理解为一个同步的原子性事务,修改state状态
  4. action:触发mutation,可进行异步操作
  5. module:模块化

2. 类vuex状态库实现

得益于vue在2.6.0版本推出的observable API,我们可以用来监听对象的数据变化,实现一个简易的状态管理

2.1 自定义状态库 CustomStore 实现

主要实现了类vuex中的state、mutation、action部分

import Vue from 'vue';
import { updateUserAPI } from 'api';

class CustomStore {
  state: {
    user: string,
    id: number
  }

  constructor() {
    const state = Vue.observable({
      user: '',
      id: 0,
    });
    this.state = state;
  }

  // mutation
  setUser(user: string) {
    this.state.user = user;
  }

  setId(id: number) {
    this.state.id = id;
  }

  // action
  async updateUser(user: string) {
    try {
      await updateUserAPI(user);
      this.setUser(user);
    } catch (e) {
      console.error(e);
    }
  }
}

export const customStore = new CustomStore();
2.2 在组件中调用

通过computed属性充当getter的角色,监听state的变化,并根据需要调整格式化返回值

<template>
  <div @click="onClick">{{ id }}:{{ user }}</div>
</template>

<script lang="ts" setup>
import { customStore } from 'CustomStore'
import { computed } from 'vue'

const id = computed(() => customStore.state.id)
const user = computed(() => customStore.state.user)

function onClick() {
  customStore.updateUser('test')
}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZTao-z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值