使用vue的朋友可能用過vuex,使用react的朋友可能用redux,好處天然不用多說,用過的都說好。
微信小程序,我去年就曾接觸過,那時候小程序連組件的概念都沒有,如今小程序彷佛更火了,也增長了不少新概念,包括自定義組件。
小程序的入口文件app.js裏會調用App()方法建立一個應用程序實例,有一些公共的、全局的數據能夠保存在app.globalData屬性裏,可是globalData並不具有響應式功能,數據變化時,不會自動更新視圖。多個頁面或者組件共享同一狀態時,處理起來也是至關麻煩的。
因此,我花了一點時間,簡單實現了一個適用於小程序的狀態管理。vue
app.jsreact
//app.js
import store from './store/index';
// 建立app
App(store.createApp({
globalData: {
userInfo: {},
todos: [{
name: '刷牙',
done: true
}, {
name: '吃飯',
done: false
}]
}
// ...其餘
}))
複製代碼
pages/index/index.wxmlvuex
<view class="container">
<view>
{{title}}
</view>
<view class="info">
<view>
姓名:{{userInfo.name}}
</view>
<view>
年齡:{{userInfo.age}}
</view>
</view>
<button type="button" bindtap="addTodo">增長todo</button>
<!-- todos組件 -->
<todos />
</view>
複製代碼
pages/index/index.jsredux
//index.js
import store from '../../store/index';
// 建立頁面
Page(store.createPage({
data: {
title: '用戶信息頁'
},
// 依賴的全局狀態屬性 這些狀態會被綁定到data上
globalData: ['userInfo', 'todos'],
// 這裏能夠定義須要監聽的狀態,作一些額外的操做,this指向了當前頁面實例
watch: {
userInfo(val) {
console.log('userInfo更新了', val, this);
}
},
onLoad() {
this.getUserInfo().then(userInfo => {
// 經過dispatch更新globalData數據
store.dispatch('userInfo', userInfo);
})
},
// 模擬從服務端獲取用戶信息
getUserInfo() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
name: '小明',
age: 20
})
}, 100)
})
},
// 增長todo
addTodo() {
// 注意:這裏從this.data上獲取todos而不是globalData
const todos = [...this.data.todos, {
name: '學習',
donw: false
}];
store.dispatch('todos', todos);
}
// 其餘...
}))
複製代碼
components/todos/index.wxml小程序
<view class="container">
<view class="todos">
<view wx:for="{{todos}}" wx:key="{{index}}">
<view>{{item.name}}</view>
<view>{{item.done?'已完成':'未完成'}}</view>
</view>
</view>
</view>
複製代碼
components/todos/index.js微信小程序
import store from '../../store/index';
// 建立組件
Component(store.createComponent({
// 依賴的全局狀態屬性
globalData: ['todos'],
// 這裏能夠定義須要監聽的狀態,作一些額外的操做,this指向了當前組件實例
watch: {
todos(val) {
console.log('todos更新了', val, this);
// 作其餘事。。。
}
}
// 其餘...
}))
複製代碼
點擊"增長todo"以前bash
點擊"增長todo"以後是否是很神奇,全是代碼中那個store的功勞。
原理其實很是簡單,實現起來也就100+行代碼。
主要就是使用觀察者模式(或者說是訂閱/分發模式),經過dispatch方法更新數據時,執行回調,內部調用this.setData方法更新視圖。 很少說,直接貼一下源碼。微信
store/observer.jsapp
const events = Symbol('events');
class Observer {
constructor() {
this[events] = {};
}
on(eventName, callback) {
this[events][eventName] = this[events][eventName] || [];
this[events][eventName].push(callback);
}
emit(eventName, param) {
if (this[events][eventName]) {
this[events][eventName].forEach((value, index) => {
value(param);
})
}
}
clear(eventName) {
this[events][eventName] = [];
}
off(eventName, callback) {
this[events][eventName] = this[events][eventName] || [];
this[events][eventName].forEach((item, index) => {
if (item === callback) {
this[events][eventName].splice(index, 1);
}
})
}
one(eventName, callback) {
this[events][eventName] = [callback];
}
}
const observer = new Observer();
export {
Observer,
observer
}
複製代碼
store/index.js學習
import {
Observer
} from './observer'
const bindWatcher = Symbol('bindWatcher');
const unbindWatcher = Symbol('unbindWatcher');
class Store extends Observer {
constructor() {
super();
this.app = null;
}
// 建立app
createApp(options) {
const {
onLaunch
} = options;
const store = this;
options.onLaunch = function (...params) {
store.app = this;
if (typeof onLaunch === 'function') {
onLaunch.apply(this, params);
}
}
return options;
}
// 建立頁面
createPage(options) {
const {
globalData = [],
watch = {},
onLoad,
onUnload
} = options;
const store = this;
// 保存globalData更新回調的引用
const globalDataWatcher = {};
// 保存watch監聽回調的引用
const watcher = {};
// 劫持onLoad
options.onLoad = function (...params) {
store[bindWatcher](globalData, watch, globalDataWatcher, watcher, this);
if (typeof onLoad === 'function') {
onLoad.apply(this, params);
}
}
// 劫持onUnload
options.onUnload = function () {
store[unbindWatcher](watcher, globalDataWatcher);
if (typeof onUnload === 'function') {
onUnload.apply(this);
}
}
delete options.globalData;
delete options.watch;
return options;
}
// 建立組件
createComponent(options) {
const {
globalData = [],
watch = {},
attached,
detached
} = options;
const store = this;
// 保存globalData更新回調的引用
const globalDataWatcher = {};
// 保存watch監聽回調的引用
const watcher = {};
// 劫持attached
options.attached = function (...params) {
store[bindWatcher](globalData, watch, globalDataWatcher, watcher, this);
if (typeof attached === 'function') {
attached.apply(this, params);
}
}
// 劫持detached
options.detached = function () {
store[unbindWatcher](watcher, globalDataWatcher);
if (typeof detached === 'function') {
detached.apply(this);
}
}
delete options.globalData;
delete options.watch;
return options;
}
// 派發一個action更新狀態
dispatch(action, payload) {
this.app.globalData[action] = payload;
this.emit(action, payload);
}
/**
* 1. 初始化頁面關聯的globalData而且監聽更新
* 2. 綁定watcher
* @param {Array} globalData
* @param {Object} watch
* @param {Object} globalDataWatcher
* @param {Object} watcher
* @param {Object} instance 頁面實例
*/
[bindWatcher](globalData, watch, globalDataWatcher, watcher, instance) {
const instanceData = {};
for (let prop of globalData) {
instanceData[prop] = this.app.globalData[prop];
globalDataWatcher[prop] = payload => {
instance.setData({
[prop]: payload
})
}
this.on(prop, globalDataWatcher[prop]);
}
for (let prop in watch) {
watcher[prop] = payload => {
watch[prop].call(instance, payload);
}
this.on(prop, watcher[prop])
}
instance.setData(instanceData);
}
/**
* 解綁watcher與globalDataWatcher
* @param {Object} watcher
* @param {Object} globalDataWatcher
*/
[unbindWatcher](watcher, globalDataWatcher) {
// 頁面卸載前 解綁對應的回調 釋放內存
for (let prop in watcher) {
this.off(prop, watcher[prop]);
}
for (let prop in globalDataWatcher) {
this.off(prop, globalDataWatcher[prop])
}
}
}
export default new Store()
複製代碼
具體的代碼就不解釋了,源碼裏也有基本的註釋。 目前實現的功能不算多,基本上能用了,若是業務上需求更高了,再進行拓展。 以上, 但願能給一些朋友一點點啓發,順便點個贊哦,嘻嘻!