各页面/组件间的数据共享。
安装npm包步骤:
(图一)
- 打开编译器,在文件列表空白处点击右键,选择“在外部终端窗口中打开”(如图一中:1 )
- 执行命令: npm init -y ,初始化一个package.json。( 项目中已有package.json 文件忽略此条) 。(图一中:2 的文件)
- 有了package.json后, 执行命令:npm install --save mobx-miniprogram@4.13.2 mobx-miniprogram-bindings@1.2.1 【 安装 mobx-miniprogram 和 mobx-miniprogram-bindings包(此处为指定版本的写法,不指定版本的话不需要加 @版本号 )】。(图一中:3处可以看到安装版本)
- 在project.config.json文件中,将packNpmManually改为true,packNpmRelationList中的路径改为“./”(新版本会放到目录下,路径不对,下步构建npm的时候会报错:找不到xxxxxxx)
- 执行完成后,删除miniprogram_npm文件夹(如果有的话),打开编译器中的 工具 -- 构建npm(如图一),重新构建 -- 构建后即可使用安装包(不构建的话,node_modules文件中的包不会打到miniprogram_npm文件中,所以不会执行)。(如下图二)
- 旧版本的话需要打开编译器右上角的:详情 -- 使用 npm 的勾选。 新版本可以直接使用,不需要去详情中手动勾选
(图二)
使用
- 在根目录中创建 store 文件夹,文件夹下创建store.js 文件
- store.js文件中引入mobx-miniprogram中的 observable、action。
// store.js 文件: /* 创建store实例对象: * observable 中添加字段、计算属性、方法等 * 计算属性:用get定义,( 且只读,不能修改 ) * action方法:修改store中的值 */ import { observable, action } from 'mobx-miniprogram' export const store = observable({ // 字段/数据 store_count1: 1, store_count2: 2, // 计算属性:用get定义,(只读不能修改) get store_count_sum() { return this.store_count1 + this.store_count2 }, // action方法:用来修改store中的值 update_storecount1: action(function (step) { this.store_count1 += step }) })
- 使用"store.js共享数据"页面的.js文件中:
- 引入store.js文件及 mobx-miniprogram-bindings中的createStoreBindings方法(参数如下),并将其挂在到storeBindings变量上(页面卸载的时候做清理使用)。
- 将方法绑定到createStoreBindings方法的fields与actions上。
- 用 this.方法 / this.属性 调用。
// 调用页面的 .js文件: /* createStoreBindings:创建时,绑定到 storeBindings 变量上,是为了页面卸载的时候做清理使用 * 第一个参数: this:绑定到当前页面实例中, * 第二个参数(对象): store:数据源(将store中的某些字段、方法绑定到当前页面中) fields:将哪些字段绑定到此页面中进行使用 actions:将哪些方法绑定到此页面中 * 清理:调用 destroyStoreBingds 方法 destroyStoreBingds:清理createStoreBindings */ import { createStoreBindings } from "mobx-miniprogram-bindings" import { store } from '../../store/store.js' Page({ addcount1(e) { // 获取传入值: e.target.dataset 【 可打印 e : console.log(e)】 // 通过 this.update_storecount1:调用 action 中的 update_storecount1 方法 this.update_storecount1(e.target.dataset.addstep) }, onLoad: function (options) { this.storeBindings = createStoreBindings(this, { store, fields: ['store_count1', 'store_count2', 'store_count_sum'], actions: ['update_storecount1'] }) }, onUnload: function () { this.storeBindings.destroyStoreBingds() }, })
- 使用"store.js共享数据"页面的.wxml文件中显示:
<!-- 获取 store 中共享数据 --> <view>{{store_count1}} + {{store_count2}} = {{store_count_sum}}</view> <!-- 绑定addcount1方法,传入+=Num。 方法中: 1.在e.target.dataset中获取传入的数据。 2. 执行storeBindings变量 action中的 update_storecount1 方法,让store中的store_count1 +2 --> <button bindtap="addcount1" data-addStep='{{2}}'>store_count1 +1</button>
(操作效果:点击页面中’store_count1 +1‘按钮,store_count1会与store_count_sum的值一起增加)