小程序状态管理解决方案
发布于 4 年前 作者 pingding 3065 次浏览 来自 分享

开发《睡前故事》小程序过程中,产生这样一个需求:

  1. 循环播放音乐时,会产生历史记录,希望在我的页面查看的历史记录是同步刷新的;
  2. 使用全局变量时,切换页面需要手动给data赋值,不能直接引用;
  3. 创建的全局变量,每次更新页面值,还要手动更新 store 中的值,不能同时更新;

本着不影响原有功能,方便使用,易于扩展的原则,最终成型了这样一个小程序工具库。
目前已经满足个人项目需要,功能后续会持续优化,女朋友生日临近,生日礼物还没完成,加油。

项目介绍

小程序响应式开发解决方案。

目前已支持以下功能。

  • 数据驱动
  • mixins(混入)
  • 状态管理(全局 store)
  • effect(副作用)

源码地址

安装

1. NPM 安装

npm i [@minipro](/user/minipro)/reactivity --save

安装完成后,使用小程序开发工具构建 NPM 即可。

2. 复制文件

下载源码后,将 reactivity/dist 中文件复制到自己的项目中即可。

使用案例

1. 数据驱动

const { createPage, reactive } = require('[@minipro](/user/minipro)/reactivity');

const student = reactive({
  name: '张三'
});

createPage()({
  $data: () => {
    return {
      name: student.name
    }
  },

  onLoad: function () {
    setTimeout(() => {
      student.name = '李四';
    }, 3 * 1000)
  },
})

代码片段

2. mixins

const { createPage, reactive } = require('[@minipro](/user/minipro)/reactivity');

const student = reactive({
  name: '张三'
});

const commonMixin = {
  data: () => {
    return {
      name: student.name
    }
  },
  methods: {
    test () {
      console.log('test.');
    }
  }
}

createPage()({
  mixins: [
    commonMixin
  ],

  onLoad: function () {
    this.test();

    setTimeout(() => {
      student.name = '李四';
    }, 3 * 1000)
  },
})

代码片段

3. 状态管理

1. 创建store
import { Store } from '[@minipro](/user/minipro)/reactivity';

export default new Store({
  state: {
    student: {
      name: '张三'
    },
    count: 0
  },
  mutations: {
    changeState: (state, data) => {
      Object.keys(data).forEach(key => (state[key] = data[key]));
    }
  }
});
2. 全局注册 store(app.js)
import store from './store/index';

App({
  $store: store
})
3. 页面使用
const { createPage } = require('[@minipro](/user/minipro)/reactivity');

createPage()({
  $data: (ctx) => {
    const state = ctx.$store.state;

    return {
      student: state.student,
      count: state.count
    }
  },

  onLoad: function () {
    let timer = setInterval(() => {
      const count = this.data.count;

      if (count === 10) {
        return clearInterval(timer)
      };

      this.$store.commit('changeState', {
        count: count + 1
      })
    }, 1 * 1000);

    setTimeout(() => {
      this.$store.commit('changeState', {
        student: {
          name: '李四'
        }
      });
    }, 3 * 1000)
  },
})

代码片段

4. 副作用函数

const { createPage, reactive, effect } = require('[@minipro](/user/minipro)/reactivity');

const student = reactive({
  name: '张三'
});

createPage()({
  $data: () => {
    return {
      name: student.name
    }
  },

  onLoad: function () {
    effect(() => {
      console.log('effect:', student.name);
    });

    setTimeout(() => {
      student.name = '李四';
    }, 5 * 1000)
  },
})

代码片段

总结

开源不易,且用且珍惜。

附上《睡前故事》最新UI,后续会开源这个小程序项目。



3 回复

怎么理解“响应式”三字啊。

点赞,不错

回到顶部