Table of contents
1. How to use npm packages in applets
Now let's see how to use the npm package in the applet
3. Use the components in the vant package
2. Customize the theme of the vant component
3. Promise of the API of the applet
1. Why Promiseization is needed
2. Use a third-party package to implement Promise
3. Global data sharing (data management)
1. Install the corresponding package
2. Create the store instance object of mobx
3. Use mobx data in components
Subcontracted project composition:
Subpackage size limit: (will cause the applet to fail to be released successfully)
1. Configure the app.json file
2. Add the corresponding tabBar file (note that components are added here)
3. Use the tabBar of the Vant Weapp component library
1. How to use npm packages in applets
First of all, let’s talk about the limitations of using npm packages for small programs. Although small programs have become more and more perfect, they have many limitations after all, and not all npm packages can be used.
-
Packages that depend on Node.js built-in libraries are not supported
-
Packages that depend on browser built-in objects are not supported
-
Packages that depend on C++ plugins are not supported
Now let's see how to use the npm package in the applet
1. Create a package manager
Need to use npm package, first the project directory must have a package manager: package.json file, so the first step is to create a package manager first
You can right-click in the blank space of the project directory to open the terminal, and then use the npm initialization command to create a package management tool
npm init -y
Then you can download the package
I downloaded a vant-weapp component package here
npm i @vant/weapp -S --production
2. Build npm package
Open the WeChat developer tools, click Tools -> Build npm , after the build is complete, you can import components.
3. Use the components in the vant package
Using the components in vant is actually the same as our custom components, first introduce and use
We can import globally or locally
Global import only needs to introduce such a configuration in the app.json file
"usingComponents": {
"van-button": "@vant/weapp/button/index"
}
It can be used in the page, like this
<van-button type="primary">按钮</van-button>
a button appears
2. Customize the theme of the vant component
There is a danger button here. Its default color is red. If we want to change its color, we can configure it globally in app.wxss or in the page wxss
page{
--button-danger-background-color:black;
--button-danger-border-color: black;
}
After this configuration, the color of the button has changed
For details, all configurations can refer to the official document: vant-weapp/packages/common/style/var.less at dev youzan/vant-weapp GitHub
All configuration items are sorted alphabetically, so it is easy to find
3. Promise of the API of the applet
1. Why Promiseization is needed
By default, the asynchronous APIs officially provided by Mini Programs are implemented based on callback functions. For example, APIs for network requests need to be called as follows:
If the data is large, this kind of callback function will be used extensively, and it will fall into the problem of callback hell, so Promise is needed to solve this problem
2. Use a third-party package to implement Promise
Third-party packages used:
npm i --save [email protected]
After downloading the package, you need to rebuild npm to use the package
Use this package to implement Promise in the project
Reference the following code in App.js
import {promisifyAll} from 'miniprogram-api-promise'
const wxp = wx.p = {}
promisifyAll(wx,wxp)
In this way, we can realize Promise when using WeChat API
Test Case:
getList(){
const res = wx.p.request({
url: 'https://applet-base-api-t.itheima.net/api/get',
method:'GET',
data:{
name:'zs',
age:20
},
})
console.log(res);
},
Print the result: you can see that it has been Promiseized at this time
After further use of async and await
Printing the result is already a very standard Promise
3. Global data sharing (data management)
Global data sharing, that is, storing all data in one place for use by all components and pages
We use Vuex the most in Vue , and we use mobx in small programs
1. Install the corresponding package
npm install --save [email protected] [email protected]
Rebuild npm after installation
2. Create the store instance object of mobx
First create a store folder in the project directory, then create a store.js file, and write some data sharing in it
Code example:
import { action } from 'mobx-miniprogram'
import {observable} from 'mobx-miniprogram '
export const store = observable({
//数据字段
numA : 1,
numB : 2,
//计算属性,这里不能修改数据
get sum(){
return this.numA + this.numB
},
//actions 方法 ,用来修改数据
updateNumA:action(function(step){
this.numA += step
}),
updateNumB:action(function(step){
this.numB += step
})
})
3. Use mobx data in the page
Introduce on demand in the js of the page
import {createStoreBindings} from 'mobx-miniprogram-bindings'
import {store} from '../../store/store'
Page({
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.storeBindings = createStoreBindings(this, {
store,
fields:['numA','numB','sum'], //要传递过来的数据
actions:['updateNumA','updateNumB'] //要传递过来的方法
})
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
this.storeBindings.detroyStoreBindings()
},
})
In this way, the data in the store is obtained in the page and can be used directly
<view>{
{numA}} + {
{numB}} = {
{sum}}</view>
<van-button type="primary" bindtap="btnHandler1" data-step="{
{1}}">numA +1</van-button>
<van-button type="danger" bindtap="btnHandler1" data-step="{
{-1}}">numA -1</van-button>
This function is used to call the updateNumA method passed from the store
btnHandler1(e){
this.updateNumA(e.target.dataset.step)
},
3. Use mobx data in components
The first is to introduce the store in the js of the component
import {storeBindingsBehavior} from 'mobx-miniprogram-bindings'
import {store} from '../../store/store'
Component({
behaviors: [storeBindingsBehavior], //绑定store
storeBindings:{
store,
fields: {
numA: 'numA', //绑定store中的数据和计算属性
numB: 'numB',
sum: 'sum'
},
actions: {
updateNumA: 'updateNumA' //绑定actions方法
}
},
})
Then you can use it in the same way as in the page
Four, subcontracting
Subpackaging refers to dividing a complete small program project into different subpackages according to requirements, packaging them into different subpackages during construction, and loading them as needed when users use them.
Advantages of subcontracting:
- Can optimize the download time for the first startup of the applet
- Collaborate better when multiple teams develop together
Subcontracted project composition:
Subpackage size limit: (will cause the applet to fail to be released successfully)
The size of all subpackages of the entire applet does not exceed 16M (main package + all subpackages)
The size of a single subpackage/main package cannot exceed 2M
Subpackage configuration: add the code in the red box to app.json , and after saving, the corresponding subpackage and page will be automatically generated
Check the subpackage volume: just check it in the basic information on the details page
Quotation rules after subcontracting:
①The main package cannot reference the private resources in the sub-package
② Subcontracts cannot refer to each other's private resources
③ Subpackages can refer to public resources in the main package
For details, see the project structure diagram above
Independent Subcontract:
An independent subpackage is essentially a subpackage, but its advantage is that it can run independently of the main package. Generally, when users access a small program, they first open the main package, that is, the main page, and then access other subpackages. The package page can be accessed directly without relying on the main package after independent subcontracting
To distinguish between ordinary packages and independent packages, you only need to add such a sentence in the subpackage
Citation principles for independent subcontracting:
①The main package cannot refer to the private resources in the independent sub-package between independent sub-packages
② Do not quote private resources from each other
③ Private resources cannot be referenced to each other between independent subcontracts and ordinary subcontracts. Special attention: public resources in the main package cannot be referenced in independent subcontracts
Subpackage pre-download:
Sub-package pre-download means that when we enter a certain page, let it automatically download the packages that may be needed later, so that when our user u needs to use it, it can be rendered faster and increase the user experience
To configure subpackage pre-download, you only need to configure the following sample code in app.json
Five, custom tabBar case
1. Configure the app.json file
Add the following code to open the custom tabBar, but the original configuration below cannot be deleted. In order to ensure compatibility with lower versions and distinguish which pages are tab pages, the relevant configuration items of the tabBar need to be fully declared, but these fields will not be applied to Customize the rendering of the tabBar.
2. Add the corresponding tabBar file (note that components are added here)
3. Use the tabBar of the Vant Weapp component library
①: Add the corresponding components in the app.json file
②: Add the corresponding wxml
<!--custom-tab-bar/index.wxml-->
<van-tabbar active="{
{ active }}" bind:change="onChange">
<van-tabbar-item info="3">
<image slot="icon" src="{
{ icon1.normal }}" mode="aspectFit" style="width: 30px; height: 18px;" />
<image slot="icon-active" src="{
{ icon1.active }}" mode="aspectFit" style="width: 30px; height: 18px;" />
首页
</van-tabbar-item>
<van-tabbar-item info="3">
<image slot="icon" src="{
{ icon2.normal }}" mode="aspectFit" style="width: 30px; height: 18px;" />
<image slot="icon-active" src="{
{ icon2.active }}" mode="aspectFit" style="width: 30px; height: 18px;" />
消息
</van-tabbar-item>
<van-tabbar-item info="3">
<image slot="icon" src="{
{ icon3.normal }}" mode="aspectFit" style="width: 30px; height: 18px;" />
<image slot="icon-active" src="{
{ icon3.active }}" mode="aspectFit" style="width: 30px; height: 18px;" />
联系我们
</van-tabbar-item>
</van-tabbar>
③: Add the corresponding js code
Page({
data: {
active:0,
icon1: {
active: '/images/tabs/home-active.png', //未选中的图标
normal: '/images/tabs/home.png',//选中的图标
},
icon2:{
active: '/images/tabs/message-active.png', //未选中的图标
normal: '/images/tabs/message.png',//选中的图标
},
icon3:{
normal: '/images/tabs/contact.png', //未选中的图标
active: '/images/tabs/contact-active.png',//选中的图标
}
},
onChange(event) {
// event.detail 的值为当前选中项的索引
this.setData({ active: event.detail });
},
});
The tabBar effect appears