Code Monkey home page Code Monkey logo

atomu's Introduction

atomu

npm version npm downloads npm license

一个轻量级微信小程序状态管理库。

安装

通过 npm:

npm install atomu

用例

创建 store

const { createStore } = require('atomu');

const store = createStore({
  state: {
    count: 0,
  },

  actions: {
    increment({ set, get }) {
      set({ count: get().count });
    },
  },
});

组件中使用

在逻辑层中,绑定 store:

Component({
  lifetimes: {
    attached() {
      this.$store = store.bind(this, ['count'], '$store');
    },

    detached() {
      this.$store.unbind();
    },
  },

  methods: {
    increment() {
      this.$store.dispatch('increment');
    },
  },
});

完成绑定后,可以在视图层中轻松访问并使用 store 中存储的状态:

<button wx:bind="increment">count: {{ $store.count }}</button>

TIP: 组件销毁后,请务必手动进行解绑操作,以避免潜在的内存泄漏问题。

携带载荷

actions 可以接收 dispatch 方法传递的载荷,从而灵活处理各种业务逻辑:

actions: {
  increment({ set, get }, payload) {
    set({ count: payload });
  }
}

store.dispatch('increment', 0)

异步提交更新

actions 支持异步操作:

actions: {
  async increment({ set, get }) {
    // await ...
    set({ count: get().count });
  }
}

调用 dispatch 方法时,会返回一个 Promise 实例,能够方便地判断异步 action 的执行状态:

store
  .dispatch('increment')
  .then(() => {
    // ...
  })
  .catch(() => {
    // ...
  });

订阅状态更新

Component({
  lifetimes: {
    attached() {
      this.unsubscribe = store.subscribe((mutation, state) => {
        console.log(mutation, state);
      });
    },

    detached() {
      this.unsubscribe();
    },
  },
});

绑定多个 store

Component({
  lifetimes: {
    attached() {
      this.$store = store.bind(this, ['count'], '$store');
      this.$user = user.bind(this, ['profile'], '$user');
    },

    detached() {
      this.$store.unbind();
      this.$user.unbind();
    },
  },
});

API

bind

  • bind(ctx: Component | Page, stateKeys?: string[], namespace?: string)

bind 方法用于将 store 中的状态绑定到组件中,通过 stateKeys 参数,可以指定需要绑定的具体状态(若未指定,则默认绑定 store 中的所有状态)。而 namespace 则用于为绑定的状态创建一个独立的空间,确保在状态更新时仅更新该空间内的状态,这在同时绑定多个 store 时尤为实用,有助于避免状态之间的混淆和冲突。

bind 方法所绑定的状态都会自动存储在组件的 data 对象中,方便在组件内部直接使用这些状态数据:

Component({
  lifetimes: {
    attached() {
      this.$store = store.bind(this, ['count'], '$store');
    },

    detached() {
      this.$store.unbind();
    },
  },

  methods: {
    increment() {
      // 访问状态
      this.$store.dispatch('increment', this.data.$store.count);
    },
  },
});

getState

  • getState()

getState 方法用于在组件外部获取状态:

store.getState();

插件

Logger

日志插件用于一般的调试:

const { createLogger } = require('atomu');

const store = createStore({
  plugins: [createLogger()],
});

createLogger 函数有几个配置项:

createLogger({
  collapsed: false, // 自动展开记录的 mutation
  filter(mutation, state) {
    // 若 mutation 需要被记录,就让它返回 true 即可
    // `mutation` 的格式是 `{ type, payload }`
    return mutation.type !== 'ignore';
  },
  logger: console, // 自定义 console 实现,默认为 `console`
});

Persisted State

持久化插件用于本地缓存 store 中的状态:

const { createPersistedState } = require('atomu');

const store = createStore({
  plugins: [createPersistedState()],
});

createPersistedState 函数有几个配置项:

createPersistedState({
  key: 'atomu', // 本地缓存中指定的 key
  filter(mutation, state) {
    // 若 mutation 需要被记录,就让它返回 true 即可
    // `mutation` 的格式是 `{ type, payload }`
    return mutation.type !== 'ignore';
  },
});

atomu's People

Contributors

985563349 avatar

Stargazers

longmo avatar yangbo avatar  avatar qqf avatar  avatar YXW avatar xingxing avatar Hannah Jensen avatar Wang Yi avatar

Watchers

 avatar

atomu's Issues

是否考虑在 js 文件中支持便捷访问 state 中的数据呢?

遇到的场景,比如将商家和门店数据存储到 store 的 state 中,在请求拦截器需要获取某个 store 的 state 存储的数据,没有很好的方式,内部只对外暴漏了 bind、dispatch 和 订阅。

atomu 目前支持最好的场景是结合 Page 和 Component 使用。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.