在小程序中使用状态管理mobx
在小程序中使用状态管理mobx
使用mobx后,进入二级页面修改数据返回一级页面显示的数据跟着变
先看效果
控制台打印的数据
以下是代码
store.js
// js/store.js // 手动安装时引入的路径 import {configure, extendObservable} from "./mobx"; // 设置可在任何地方修改 configure({ enforceActions: 'never', }); let Store = function () { /*属性*/ extendObservable(this, { // observable data todoText: 'aaa', // computed data get todoTextCount() { return this.todoText.length; } }); /*方法*/ // action this.changeTodoText = function (todoText) { this.todoText = todoText; } } module.exports.store = new Store
test.js
// pages/test/test.js import { autorun } from '../../js/mobx'; import { store } from '../../js/store'; Page({ data: { todoText: store.todoText, }, // your other code below onLoad: function (evt) { this._autorun(); const _this = this; console.log('onLoad', evt); // this._autorun(); store.changeTodoText('test.store.111'); store.todoText = 'test.store.222'; }, _disposer: [], _autorun: function () { const _this = this; _this._disposer.push( autorun(function () { console.log('autorun.todoText', _this.data, store); _this.setData({ todoText: store.todoText }); }) ); }, onUnload: function (evt) {
this._disposer.map(function (x) { x() }); this._disposer.length = 0; }, onJumpAaa: function (evt) { tt.navigateTo({ url: '/pages/aaa/aaa' // 指定页面的url }); } })
aaa.js
// pages/aaa/aaa.js import { autorun } from "../../js/mobx"; import { store } from "../../js/store"; Page({ data: { todoText: store.todoText, }, // your other code below onLoad: function (evt) { this._autorun(); const _this = this; console.log('onLoad', evt); store.changeTodoText('aaa.store.111'); store.todoText = 'aaa.store.222'; }, _disposer: [], _autorun: function () { const _this = this; _this._disposer.push( autorun(function () { console.log('autorun.todoText', _this.data, store); _this.setData({ todoText: store.todoText }); }) ); }, onUnload: function (evt) {
this._disposer.map(function (x) { x() }); this._disposer.length = 0; }, })
本文链接: