44、API Promise化
(1)基于回调函数的一部API的缺点:小程序官方提供的异步API都是基于回调函数实现的,容易造成回调地狱的问题,代码可读性、可维护性差
(2)API Promise化概念:
指的是通过额外的配置,将官方提供的、基于回调函数的异步API,升级改造为基于Promise的异步API,提高代码的可读性、可维护性,避免回调地狱的问题。
(3)实现API Promise化(主要依赖于miniprogram-api-promise第三方包)
1)miniprogram-api-promise的安装(npm i --save miniprogram-api-promise@1.0.4)

2)在外部资源管理器删除miniprogram_npm包,重新构建npm
①删除miniprogram_npm包

②重新构建npm

显示:


3)在app.js文件中,导入并使用promisifyAll
①导入promisifyAll

②使用promisifyAll

(4)调用Promise化后的异步API



45、全局数据共享(状态管理)
(1)作用:解决组件之间数据共享的问题,比如:Vuex、Redux、MobX
(2)原理:
1)通过mobx-miniprogram创建Store实例对象
2)通过mobx-miniprogram-bindings把Store中的共享数据或方法,绑定到组件或页面中使用
(3)安装Mobx相关包,并进行npm重建
1)执行命令,安装mobx包(npm i --save mobx-miniprogram@4.13.2 mobx-miniprogram-bindings@1.2.1)

2)删除miniprogram_npm包

3)重新构建npm
(4)创建Mobx的Store实例
1)在store文件夹下的js文件中,导入observable,导出空实例

2)定义可以提供的数据、计算属性和actions方法
①数据

②计算属性(方法前,必须加get)

③actions方法(需要导入action,然后使用)


3)在页面中使用Store
①在所需页面导入createStoreBindings、store

②在onLoad方法中挂载所需字段、计算属性、方法

示例:

③在onUnload方法中,销毁实例

④在页面使用


效果:

4)将Store中的成员绑定到组件中
①导入storeBindingsBehavior和store

②实现自动绑定

③绑定字段、方法

④使用(在所需组件内使用,将组件渲染到页面)


46、分包
(1)概念:把一个完整的小程序项目按照不同的需求划分为不同的子包,在构建时打包成·不同的分包,用户使用时按需加载。
(2)优点:
1)可以优化小程序首次启动的下载时间
2)在多团队共同开发时可以更好的解耦协作
(3)分包的项目构成
1)分包前的项目构成:所有页面和公共资源
分包前,小程序的所有页面和资源都被打包到了一起,导致项目体积过大,影响小程序首次启动的下载时间
2)分包后的项目构成:1个主包+多个分包
①主包:一般只包含项目的启动页面或tabBar页面、以及所有分包都需要用到的一些公共资源
②分包:只包含和当前分包有关的页面和私有资源
(4)分包的加载规则
1)在小程序启动时,默认会下载主包,并启动主包内页面(tabBar页面需要放到主包中)
2)当用户进入分包时,客户端会把对应分包下载下来,下载完成后再进行展示(非tabBar页面可以按照功能的不同,划分为不同的分包之后,进行按需下载)
(5)分包的体积限制
1)整个小程序所有的分包大小不超过16M(主包+所有分包)
2)单个分包/主包的大小不能超过2M
(6)分包的基本用法
1)添加分包
在app.json中新增与pages平级的subpackages属性,为其配置根目录,页面路径

2)为分包命名
通过name命名

3)查看分包的体积
在"详情"的"基本信息"中,查看"本地代码"

4)打包原则
①小程序会按subpackages的配置进行分包,subpackages户外的目录将被打包到主包中
②主包也可以有自己的pages(即最外层的pages字段)
③tabBar页面必须在主包内
④分包之间不能互相嵌套
5)引用规则
①主包无法引用分包内的私有资源
②分包之间不能相互引用私有资源
③分包可以引用主包内的公共资源
(7)独立分包(一个小程序中可以有多个独立分包)
1)概念:本质上也是分包,但可以独立于主包和其他分包而单独运行
2)独立分包和普通分包的区别:是否依赖于主包才能运行
①普通分包必须依赖于主包才能运行
②独立分包可以不下载主包的情况下运行
3)应用及其原因:
①应用:开发者可以按需将某些具有一定功能的独立性页面配置到独立的分包中
②原因:当小程序从普通的分包页面启动时,需要首先下载主包,而独立分包不依赖与主包即可运行,可以很大程度上提升分包页面的启动速度 。
4)独立分包的配置
在普通分包的基础上,添加independent属性

5)引用规则(独立分包和普通分包以及主包之间是相互隔绝的,不能相互引用彼此的资源)
①主包无法引用独立分包内的私有资源
②独立分包之间,不能相互引用私有资源
③独立分包和普通分包之间,不能相互引用私有资源
④独立分包不能引用主包内的公共资源
(8)分包预下载
1)概念:在进入小程序的某个页面时,由框架自动预下载可能需要的分包,从而提升进入后续分包页面时的启动速度
2)配置分包预下载(预下载分包会在进入页面时触发):
在app.json中新增preloadRule属性,进行配置

比如:

Wifi与all


3)分包预下载的限制
同一个分包中的页面享有共同的预下载限额2M(同一页面内所有分包预下载体积之和<=2M)