微信小程序状态管理的 demo

Overview

微信小程序状态管理

基于发布订阅模式、小程序自定义组件behaviors配置 实现数据的状态管理。

这个作为demo稍微有点复杂。精简版可看 实现

应用场景

原生微信小程序开发

解决问题和实现目的

  • 全局共享的状态管理
  • 组件与页面都可订阅状态
  • 按需订阅
  • 支持异步编程
  • 不依赖插件

准备工作

小程序开发者工具-本地设置

  • ES6转ES5
  • 增强编译

如何使用

  1. 创建model文件 store/models/counter.js;类似dva的model 或 vue的module
const util = require('../../utils/util');
module.exports = {
    /* 
        状态管理-数据
    */
    state: {
        count: 0
    },
    /* 
        异步方法: return 会返回给 dispatch()
    */
    effects: {
        async delayAdd(action, { dispatch, storeState }) {
            // 延迟600ms
            await util.delay(600);
            dispatch({
                type: 'counter/add',
                payload: {
                    num: 1,
                }
            });
            return storeState.counter.count;
        },
    },
    /*
        同步方法: return 会覆盖此 model的 state
    */
    reducers: {
        add(state, { payload }) {
            return {
                ...state,
                count: state.count + payload.num
            }
        }
    }
};
  1. store中注入此model store/store.js
const createStore = require('../utils/createStore');
const counter = require('./models/counter.js');

module.exports = createStore({
    counter,
});
  1. 在页面或组件的js的订阅需要的数据
const store = require("../../store/store");
const connect = require('../../store/connect');

Component({
    /* 
        1. 这里选择需要订阅的数据。
            connect的参数: 模块名[]
    */
    behaviors: [
        connect(['counter']),
    ],
    data: {
        count: 0,
    },
    methods: {
        /*  
            2. 数据更新会触发 onStoreStateUpdate, 参数是 store 的 state
        */
        onStoreStateUpdate({ counter }) {
            this.setData({
                count: counter.count
            });
        },
        onAdd() {
            /* 
                触发数据变更
            */
            store.dispatch({
                type: 'counter/add',
                payload: {
                    num: 1
                }
            });
        },
        async onAsyncAdd() {
            /* 
                触发store的异步方法。一般方法内会再 dispatch 触发数据变更
            */
            const count = await store.dispatch({
                type: 'counter/delayAdd',
            });
        }
    }
});

store/store.js 的属性

store.state

  • store的数据状态

store.dispatch({ type, payload })

  • type: 字符串, 以/为分割符;前面是model名,后面是方法名。 '[model name]/[method]'
  • payload 传给方法的参数

store.subscribe(subscribeModelNames, subscribeCallback)

  • subscribeModelNames: string[] 订阅的model
  • subscribeCallback: function() 订阅的model发布状态改变触发的回调

必要文件的简单说明

  • utils/createStore.js createStore方法 解析注入的models,创建store。
  • store/store.js store对象。可用于获取所有数据(state); 触发状态改变(dispatch); 订阅与取消订阅(subscribe/unsubscribe)。
  • store/connect.js connect方法用于接受需要订阅model,创建 behavior。 用于组件订阅
  • store/models/* 数据模块管理文件

非必要解释

  • 关于组件标签 https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/ 虽然官网申明 ‘因为 WXML 节点标签名只能是小写字母、中划线和下划线的组合,所以自定义组件的标签名也只能包含这些字符。但我发现大写并没有影响,为了提高辨识度方便查找文件所以我的组件名是大小写组合
  • 本地设置-增强编译 是因为我习惯了async/await 的写法。
You might also like...

科技风智慧城市 Demo: http://stonerao.com/public/city/

科技风智慧城市 Demo: http://stonerao.com/public/city/

Three.js Setup Download Node.js. Run this followed commands: # Install dependencies (only the first time) npm install # Run the local server at local

Dec 2, 2022

Google Sheets as a Database - Next.js Demo

Google Sheets as a Database Use Google Sheets as a primary database for your Next.js project. Watch on YouTube or follow allong with the full Google S

Dec 8, 2022

Demo site build in Umbraco v.9.0.0-beta004 and .NET Core 5.0

Demo site build in Umbraco v.9.0.0-beta004 and .NET Core 5.0

Umbraco v9 Demo Demo site build in Umbraco v.9.0.0-beta004 and .NET Core 5.0. About this solution: This is a demo site for Umbraco v9 build in the new

Dec 18, 2022

A demo of a Shopify site using Astro and React.

Shopify + Astro + React A demo of a Shopify site using Astro and React. If you'd like to learn how it's built and how you can do the same, check out t

Dec 28, 2022

An intro to Three.js and React :) Workshop materials and demo from HackTheNorth 2021

An intro to Three.js and React :) Workshop materials and demo from HackTheNorth 2021

🚄 Speedy 3D - A Quick Intro to Three.js & React This workshop was originally created for Hack The North 2021! My personal motivation was to: learn th

Dec 17, 2021

Demo Selenium JavaScript E2E tests (end-to-end web browser automation tests)

Demo Selenium JavaScript E2E tests (end-to-end web browser automation tests)

Oct 9, 2021

bare bones demo of svelte-three

create-svelte Everything you need to build a Svelte project, powered by create-svelte; Creating a project If you're seeing this, you've probably alrea

Jul 30, 2022

Demo of Singapore buildings 3D tiles from OneMap on Mapbox GL JS.

Demo of Singapore buildings 3D tiles from OneMap on Mapbox GL JS.

Singapore buildings 3D Tiles from OneMap 3D on Mapbox GL JS This is a demo of Singapore buildings 3D tiles from OneMap 3D on Mapbox GL JS. Development

Nov 6, 2021

Heroku setup demo

Heroku setup demo

heroku-demo A basic guide to setting up a project hosted on Heroku with a PostgreSQL database using Giovanna Aveiro's and OliverJam's tutorial for Fou

Mar 31, 2022

Third-Party Authentication (Github) demo Vue 3 + TypeScript + Pinia app using Supabase

vue-supabase-tpa-demo This template should help get you started developing with Vue 3 in Vite. Recommended IDE Setup VSCode + Volar (and disable Vetur

Nov 21, 2022

A demo for E2E build piplelines in Design Systems using monorepo's and automation :zap:.

A demo for E2E build piplelines in Design Systems using monorepo's and automation :zap:.

Design System Pipelines demo What is it? A working demonstration for end-to-end build piplelines in Design Systems using Primer Primitives, Primer CSS

Oct 20, 2022

The app helps you to add todo items to your list, mark completed ones and also delete finished items. Its a handy tool for your day today activies. Check out the live demo.

The app helps you to add todo items to your list, mark completed ones and also delete finished items. Its a handy tool for your day today activies. Check out the live demo.

Todo List App The app helps you to add todo items to your list, mark completed ones and also delete finished items. Its a handy tool for your day toda

Apr 22, 2022

Demo showcasing information leaks resulting from an IndexedDB same-origin policy violation in WebKit.

Safari 15 IndexedDB Leaks Description This demo showcases information leaks resulting from an IndexedDB same-origin policy violation in WebKit (a brow

Nov 5, 2022

Next / React / TS demo to quickly create a landing page

Next / React / TS demo to quickly create a landing page

Jun 27, 2022

A simple demo of React Lottie power to 1st Loggi Frontend Show & Tell

Loggi Frontend Show & Tell - Animações com React Lottie A simple demo of React Lottie power to 1st Loggi Frontend Show & Tell This project was bootstr

Aug 4, 2022

LunaSec - Open Source Security Software built by Security Engineers. Scan your dependencies for Log4Shell, or add Data Tokenization to prevent data leaks. Try our live Tokenizer demo: https://app.lunasec.dev

LunaSec - Open Source Security Software built by Security Engineers. Scan your dependencies for Log4Shell, or add Data Tokenization to prevent data leaks. Try our live Tokenizer demo: https://app.lunasec.dev

Our Software We're a team of Security Engineers on a mission to make awesome Open Source Application Security tooling. It all lives in this repo. Here

Jan 7, 2023

Example TodoMVC app(s) to demo and learn Muban

Muban Todo MVC This repo contains multiple projects that showcase different ways of creating a Todo MVC app with Muban. It serves as an example, but a

Jul 9, 2022

Demo repo used in crash course for students learning web development.

Web Development Crash Course Hosted by Rubberdøk Preparation Following these steps prepares you to join the interactive React demo of the crash course

Sep 20, 2022

An attempt to create the simplest demo to describe a Consumer-Driven Contract Testing workflow with Pact

Let's Play with Pact Abstract This is an attempt to create the simplest demo to describe a Consumer-Driven Contract Testing workflow with Pact. Prereq

Feb 22, 2022
Owner
Ming
Ming
DOMPurify - a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. DOMPurify works with a secure default, but offers a lot of configurability and hooks. Demo:

DOMPurify DOMPurify is a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. It's also very simple to use and get started with

Cure53 10.2k Jan 7, 2023
HTML5 rich text editor. Try the demo integration at

Squire Squire is an HTML5 rich text editor, which provides powerful cross-browser normalisation in a flexible lightweight package (only 16.5KB of JS a

Neil Jenkins 4.4k Dec 28, 2022
Unite Gallery - Responsive jQuery Image and Video Gallery Plugin. Aim to be the best gallery on the web on it's kind. See demo here:

##Unite Gallery - Responsive jQuery Gallery Plugin Product Link: unitegallery.net This gallery has commercial versions for: WordPress , Joomla! , Pres

Max Valiano 531 Oct 24, 2022
A Google Clone which built with ReactJS. You can click the demo and search whatever you want!

Google Clone with ReactJS A small web app that imitate the desktop web version of google site, you can search whatever you want. Google Clone Demo Lin

Özge Coşkun Gürsucu 36 Aug 14, 2022
A Node JS Express/Serverless demo application that creates a slideshow video using the Pexels image library and Shotstack video editing API.

Shotstack Pexels Slideshow Video Demo This project demonstrates how to use the Shotstack cloud video editing API to create a video using an HTML form

Shotstack 25 Dec 9, 2022
The deck, starter project, & final demo for @lachlanjc’s talk at PrideMakers 2021.

PrideMakers 2021 The deck, starter project, & final demo for @lachlanjc’s talk at PrideMakers 2021. Starter on Glitch: https://glitch.com/~pridemakers

Lachlan Campbell 3 Sep 24, 2021
This is a demo sample of linking NODEJS via ORM and MYSQL

Demons(Demo of Nodejs with SQL) This is a demo sample of linking NODEJS with ORM and MYSQL Connecting Node to SQL is a hard task and not much help is

Shivam Sourav Jha 3 Apr 14, 2022
A demo of LaunchDarkly, React, and Vite, using the Pokémon API!

Pokémon Feature Flags demo Here's a demo for integrating feature flags into a React project! Built with React, Vite, the PokeAPI, and LaunchDarkly! Wh

Cassidy Williams 15 Jan 5, 2022
Demo of the tutorial on how to craft a fullscreen SVG crosshair mouse cursor with a special distortion effect on hover.

Crosshair Mouse Cursor Distortion Demo of the tutorial on how to craft a fullscreen SVG crosshair mouse cursor with a special distortion effect on hov

Codrops 33 Sep 23, 2022
A Chrome T-Rex game remake using javascript and threejs. Online demo: https://rossning92.github.io/t-rex

T-Rex Game in 3D A Chrome T-rex game remake using javascript and threejs. Build the code Make sure you have node 12+ installed: https://nodejs.org/en/

null 79 Dec 29, 2022