在小程序中使用狀態管理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; }, })
本文鏈接: