Develop WeChat Mini Programs from 0 to 1 (3) - Mini Program Framework Configuration

Other related articles

Develop WeChat Mini Programs from 0 to 1 (1) - Apply for an account and install the development environment
Develop WeChat Mini Programs from 0 to 1 (2) - Develop the first applet
from 0 to 1 Develop WeChat Mini Programs (3) - The configuration of the applet framework is
from 0 to
1
; ——We are
developing WeChat applet from 0 to 1 in writing (7) ——Mini program component library (improving development efficiency)
Develop WeChat applet from 0 to 1 (8) ——Actually fighting a mall project ——In writing

1. Small program framework

1.1, global configuration

1.1.1、Pages

significance:

  • It is used to specify which pages the applet consists of, and each item corresponds to the path (including file name) information of a page. The file name does not need to write a file suffix, the framework will automatically find the four files of .json, .js, .wxml, and .wxss in the corresponding location for processing.
  • To add/remove pages in the applet, you need to modify the pages array.

Development directory:
insert image description here

1.1.1.1、entryPagePath

Specify the default startup path (home page) of the applet. Common scenarios are drop-down startup from the WeChat chat list page, startup of the applet list, etc. If left blank, it will default to the first item in the pages list. The parameter with page path is not supported.

When entryPagePath is not specified, the first item of the array represents the initial page (home page) of the applet.
When entryPagePath is specified, it is the default startup path (home page) of the specified applet

The configuration is as follows:

{
    
    
  "entryPagePath": "pages/index/index"
}

1.1.1.2. How to generate pages

the first way

  • First create a folder, assuming it is info and the page is info, then the creation process is:

insert image description here

insert image description here

  • Open app.json and add the following

insert image description here

 "pages": [
    "pages/index/index",
    "pages/logs/logs",
    "pages/info/info"
  ],

The second way:

  • Add the directory directly in app.json and you will create it yourself

insert image description here

after saving
insert image description here

Summary: We can find that the second method is better, because there are many fewer steps, and you can be lazy!

1.1.2、window

  • Used to set the status bar, navigation bar, title, and window background color of the applet.
Attributes type Defaults describe
navigationBarBackgroundColor HexColor #000000 Navigation bar background color, such as #000000
navigationBarTextStyle string white Navigation bar title color, only supports black/white
navigationBarTitleText string Navigation bar title text content
backgroundColor HexColor #ffffff the background color of the window
backgroundTextStyle string dark Drop-down loading style, only supports dark / light
enablePullDownRefresh boolean false Whether to enable global pull-to-refresh. See Page.onPullDownRefresh for details
onReachBottomDistance number 50 The distance from the bottom of the page when the page bottom event is triggered, in px. See Page.onReachBottom for details
pageOrientation string portrait Screen rotation settings, support auto / portrait / landscape for details, see Response to display area changes
restartStrategy string homePage restart policy configuration
initialRenderingCache string Page initial rendering cache configuration, support static / dynamic
visualEffectInBackground string none When entering the system background, hide the page content to protect user privacy. Support hidden/none
handleWebviewPreload string static Controls when to preload the next page

. Support static / manual / auto |

Modify the window property configuration in the app.json file

"window": {
    
    
  "navigationBarBackgroundColor": "#000000",
  "navigationBarTextStyle": "white",
  "navigationBarTitleText": "新闻管理系统",
  "backgroundColor": "#000000",
  "backgroundTextStyle": "light",
  "enablePullDownRefresh":true,
  "onReachBottomDistance":60
},

Display of results:
insert image description here

1.1.3, tabBar and properties

If the applet is a multi-tab application (there is a tab bar at the bottom or top of the client window to switch pages), you can specify the performance of the tab bar and the corresponding page displayed when the tab is switched through the tabBar configuration item.

Attributes type Required Defaults describe
color HexColor Yes Default color of text on tabs, only hexadecimal colors are supported
selectedColor HexColor Yes The color of the text on the tab when it is selected, only hexadecimal colors are supported
backgroundColor HexColor Yes The background color of the tab, only hexadecimal colors are supported
borderStyle string no black The color of the border on the tabbar, only black / white is supported
list Array Yes The list of tabs, see the list attribute description for details, at least 2 and at most 5 tabs
position string no bottom The position of the tabBar, only supports bottom / top
custom boolean no false Customize tabBar, see details

Among them, list accepts an array, and only a minimum of 2 and a maximum of 5 tabs can be configured . The tabs are sorted in the order of the array, and each item is an object with the following property values:

Attributes type Required illustrate
pagePath string Yes The page path, which must be defined first in pages
text string Yes button text on tab
iconPath string no The image path, the icon size is limited to 40kb, the recommended size is 81px * 81px, and network images are not supported.
When the position is top, the icon is not displayed.
selectedIconPath string no The image path when selected, the icon size is limited to 40kb, the recommended size is 81px * 81px, and network images are not supported.
When the position is top, the icon is not displayed.

Modify the app.json configuration file and add the tabBar property configuration

"tabBar": {
    
    
    "list": [{
    
    
      "pagePath": "pages/index/index",
      "text": "首页",
      "iconPath":"./images/home.png",
      "selectedIconPath":"./images/home_select.png"
     }, {
    
    
      "pagePath": "pages/info/info",
      "text": "新闻",
      "iconPath": "./images/news.png",
      "selectedIconPath": "./images/news_select.png"
     }]
  }

Display of results:
insert image description here

1.1.4. Other common configurations

1.1.4.1、sitemapLocation

Indicate the location of sitemap.json; the default is 'sitemap.json', which is the sitemap.json file with the name in the same directory as app.json

1.1.4.2、style

The basic library 2.8.0 starts to support, and the lower version needs to be compatible.
Starting from WeChat client 7.0, the UI interface has undergone a major revision. The Mini Program has also upgraded the style of the basic components. Configure "style": "v2" in app.json to enable the new version of the component style.
The components involved in this change are button icon radio checkbox switch slider. You can go to the applet sample for experience.

1.1.4.3、networkTimeout

The timeout period for various network requests, in milliseconds.

Attributes type Required Defaults illustrate
request number no 60000 wx.request
The timeout period, in milliseconds.
connectSocket number no 60000 wx.connectSocket
The timeout period, in milliseconds.
uploadFile number no 60000 wx.uploadFile
的超时时间,单位:毫秒。
downloadFile number 60000 wx.downloadFile
的超时时间,单位:毫秒。

1.1.4.4、debug

可以在开发者工具中开启 debug 模式,在开发者工具的控制台面板,调试信息以 info 的形式给出,其信息有 Page 的注册,页面路由,数据更新,事件触发等。可以帮助开发者快速定位一些常见的问题。

1.1.4.5、functionalPages

基础库 2.1.0 开始支持,低版本需做兼容处理。
插件所有者小程序需要设置这一项来启用插件功能页

1.1.4.5、subpackages

微信客户端 6.6.0 ,基础库 1.7.3 及以上版本支持
启用分包加载时,声明项目分包结构。
写成 subPackages 也支持。

1.1.4.6、workers

基础库 1.9.90 开始支持,低版本需做兼容处理。
使用 Worker 处理多线程任务时,设置 Worker 代码放置的目录

1.1.4.7、requiredBackgroundModes

微信客户端 6.7.2 及以上版本支持
申明需要后台运行的能力,类型为数组。目前支持以下项目:

  • audio: 后台音乐播放
  • location: 后台定位

如:

{
    
    
  "pages": ["pages/index/index"],
  "requiredBackgroundModes": ["audio", "location"]
}

注:在此处申明了后台运行的接口,开发版和体验版上可以直接生效,正式版还需通过审核。

1.1.4.8、requiredPrivateInfos

自 2022 年 7 月 14 日后发布的小程序,使用以下8个地理位置相关接口时,需要声明该字段,否则将无法正常使用。2022 年 7 月 14 日前发布的小程序不受影响。
申明需要使用的地理位置相关接口,类型为数组。目前支持以下项目:

如:

{
    
    
  "pages": ["pages/index/index"],
  "requiredPrivateInfos": [
    "getFuzzyLocation", 
    "getLocation",
    "onLocationChange",
    "startLocationUpdateBackground"
    "chooseAddress"
  ]
}

注:若使用以上接口,均需在小程序管理后台,「开发」-「开发管理」-「接口设置」中自助开通该接口权限。

1.1.4.9、debugOptions(真机可看)

小程序调试相关配置项

属性 类型 必填 默认值 描述
enableFPSPanel boolean false 是否开启 FPS 面板

FPS面板:

为了便于开发者调试渲染层的交互性能,小程序基础库提供了选项开启 FPS 面板,开发者可以实时查看渲染层帧率。

开启方式:

{
    
    
  "debugOptions": {
    
    
    "enableFPSPanel": "custom"
  }
}

1.1.4.10、permission

微信客户端 7.0.0 及以上版本支持
小程序接口权限相关设置。字段类型为 Object,结构为:

属性 类型 必填 默认值 描述
scope.userLocation PermissionObject 位置相关权限声明

PermissionObject 结构

属性 类型 必填 默认值 说明
desc string 小程序获取权限时展示的接口用途说明。最长 30 个字符

如:

{
    
    
  "pages": ["pages/index/index"],
  "permission": {
    
    
    "scope.userLocation": {
    
    
      "desc": "你的位置信息将用于小程序位置接口的效果展示" // 高速公路行驶持续后台定位
    }
  }
}

app.json 文件配置如下

{
    
    
  "entryPagePath": "pages/index/index",
  "pages": [
    "pages/index/index",
    "pages/logs/logs",
    "pages/info/info",
    "pages/about/about",
    "pages/test/test"
  ],
  "window": {
    
    
    "navigationBarBackgroundColor": "#000000",
    "navigationBarTextStyle": "white",
    "navigationBarTitleText": "新闻管理系统",
    "backgroundColor": "#000000",
    "backgroundTextStyle": "light",
    "enablePullDownRefresh": true,
    "onReachBottomDistance": 60
  },
  "style": "v2",
  "sitemapLocation": "sitemap.json",
  "tabBar": {
    
    
    "list": [{
    
    
      "pagePath": "pages/index/index",
      "text": "首页",
      "iconPath": "./images/home.png",
      "selectedIconPath": "./images/home_select.png"
    }, {
    
    
      "pagePath": "pages/info/info",
      "text": "新闻",
      "iconPath": "./images/news.png",
      "selectedIconPath": "./images/news_select.png"
    }]
  },
  "networkTimeout": {
    
    
    "request": 20000,
    "connectSocket": 20000,
    "uploadFile": 20000,
    "downloadFile": 20000
  },
  "debug": true,
  "permission": {
    
    
    "scope.userLocation": {
    
    
      "desc": "你的位置信息将用于小程序位置接口的效果展示"
    }
  },
  "debugOptions": {
    
    
    "enableFPSPanel": true
  }
}

1.1.4.11、usingComponents

开发者工具 1.02.1810190 及以上版本支持
在 app.json 中声明的自定义组件视为全局自定义组件,在小程序内的页面或自定义组件中可以直接使用而无需再声明。建议仅在此声明几乎所有页面都会用到的自定义组件。
注1:全局自定义组件会视为被所有页面依赖,会在所有页面启动时进行初始化,影响启动性能且会占用主包大小。只被个别页面或分包引用的自定义组件应尽量在页面配置中声明。 注2:在全局声明使用率低的自定义组件会大幅影响按需注入的效果。

1.1.5、单页面配置(指定每个页面的标题等)

app.json 中的部分配置,也支持对单个页面进行配置,可以在页面对应的 XXX.json 文件来对本页面的表现进行配置。页面中配置项在当前页面会覆盖 app.json 中相同的配置项(样式相关的配置项属于 app.json 中的 window 属性,但这里不需要额外指定 window 字段)

文件内容为一个 JSON 对象,有以下属性:

属性 类型 默认值 描述
navigationBarBackgroundColor HexColor #000000 导航栏背景颜色,如 #000000
navigationBarTextStyle string white 导航栏标题颜色,仅支持 black / white
navigationBarTitleText string 导航栏标题文字内容
navigationStyle string default 导航栏样式,仅支持以下值:
default 默认样式
custom 自定义导航栏,只保留右上角胶囊按钮。
homeButton boolean false 在非首页、非页面栈最底层页面或非 tabbar 内页面中的导航栏展示 home 键
backgroundColor HexColor #ffffff 窗口的背景色
backgroundTextStyle string dark 下拉 loading 的样式,仅支持 dark / light
backgroundColorTop string #ffffff 顶部窗口的背景色,仅 iOS 支持
backgroundColorBottom string #ffffff 底部窗口的背景色,仅 iOS 支持
enablePullDownRefresh boolean false 是否开启当前页面下拉刷新。
详见 Page.onPullDownRefresh
onReachBottomDistance number 50 页面上拉触底事件触发时距页面底部距离,单位为px。
详见 Page.onReachBottom
pageOrientation string portrait 屏幕旋转设置,支持 auto / portrait / landscape
详见 响应显示区域变化
disableScroll boolean false 设置为 true 则页面整体不能上下滚动。
只在页面配置中有效,无法在 app.json 中设置
usingComponents Object 页面自定义组件
配置
initialRenderingCache string 页面初始渲染缓存
配置,支持 static / dynamic
style string default 启用新版的组件样式
singlePage Object 单页模式相关配置
restartStrategy string homePage 重新启动策略配置
handleWebviewPreload string static 控制预加载下个页面的时机
。支持 static / manual / auto
visualEffectInBackground string 切入系统后台时,隐藏页面内容,保护用户隐私。支持 hidden / none,若对页面单独设置则会覆盖全局的配置,详见 全局配置
enablePassiveEvent Object或boolean 事件监听是否为 passive,若对页面单独设置则会覆盖全局的配置,详见 全局配置
renderer string 渲染后端
  • 注:并不是所有 app.json 中的配置都可以在页面覆盖或单独指定,仅限于本文档包含的选项。
  • 注:iOS/Android 客户端 7.0.0 以下版本,navigationStyle 只在 app.json 中生效。

配置方式如下:

{
    
    
  "navigationBarBackgroundColor": "#ffffff",
  "navigationBarTextStyle": "black",
  "navigationBarTitleText": "微信接口功能演示",
  "backgroundColor": "#eeeeee",
  "backgroundTextStyle": "light"
}

index.json文件中的配置如下:

{
    
    
  "usingComponents": {
    
    },
  "navigationBarBackgroundColor": "#ffffff",
  "navigationBarTextStyle": "black",
  "navigationBarTitleText": "微信接口功能演示",
  "backgroundColor": "#eeeeee",
  "backgroundTextStyle": "light"
}

展示效果为:
insert image description here
insert image description here

1.1.6、公共样式(全局改变)

  • 在项目根目录的 app.wxss 文件为小程序公的共样式表,相当与CSS初始化文件配置
  • WXSS (WeiXin Style Sheets)是一套样式语言,用于描述 WXML 的组件样式
  • WXSS 用来决定 WXML 的组件应该怎么显示
  • 为了适应广大的前端开发者,WXSS 具有 CSS 大部分特性。同时为了更适合开发微信小程序,WXSS 对 CSS 进行了扩充以及修改。
  • 与 CSS 相比,WXSS 扩展的特性有:
    • 尺寸单位
    • 样式导入

1.1.6.1、公共样式

在 app.wxss 文件中添加样式

text{
    
    
  color:red;
}

项目中所有的页面的 text 文本都会呈现红色

1.1.6.2、尺寸单位

rpx(responsive pixel): 可以根据屏幕宽度进行自适应。规定屏幕宽为750rpx。如在 iPhone6 上,屏幕宽度为375px,共有750个物理像素,则750rpx = 375px = 750物理像素,1rpx = 0.5px = 1物理像素

设备 rpx换算px (屏幕宽度/750) px换算rpx (750/屏幕宽度)
iPhone5 1rpx = 0.42px 1px = 2.34rpx
iPhone6 1rpx = 0.5px 1px = 2rpx
iPhone6 Plus 1rpx = 0.552px 1px = 1.81rpx

建议: 开发微信小程序时设计师可以用 iPhone6 作为视觉稿的标准。
注意: 在较小的屏幕上不可避免的会有一些毛刺,请在开发时尽量避免这种情况
在news页面的wxml文件中增加下列代码

<view class="box"></view>

在 app.wxss 文件中,增加box盒子的样式

.box{
    
    
  width: 200rpx;
  height: 200rpx;
  background: red;
}

在iphone5上的效果,元素的宽高是85px
insert image description here

在iphone6上的效果,元素的宽高是100px
insert image description here

1.1.6.3、样式导入

使用@import语句可以导入外联样式表,@import后跟需要导入的外联样式表的相对路径,用;表示语句结束
在项目根目录下创建common文件夹,并创建common.wxss文件,增加box的样式

.box{
    
    
  margin: 50px;
}

在app.wxss文件中引入common.wxss文件

@import "./common/common.wxss";

此时,刚刚所创建的box也加载了引入文件的样式。
insert image description here

1.1.7、注册小程序

每个小程序都需要在 app.js 中调用 App 方法注册小程序实例,绑定生命周期回调函数、错误监听和页面不存在监听函数等。

// app.js
App({
    
    
  onLaunch(options) {
    
    
    console.log("监听小程序初始化", options);
  },
  onShow(options) {
    
    
    console.log("监听小程序启动", options);
  },
  onHide() {
    
    
    console.log("监听小程序切后台");
  },
  onError(msg) {
    
    
    // 小程序发生脚本错误或 API 调用报错时触发
    console.log("错误监听函数", msg)
  },
  onPageNotFound(res) {
    
    
    console.log("页面不存在监听函数");
  },
  onThemeChange() {
    
    
    console.log("系统切换主题时触发");
  }
})

展示效果为:
insert image description here

1.1.8、全局属性

There is only one App instance in the whole applet, which is shared by all pages. The developer can obtain the globally unique App instance through the getApp method, obtain the data on the App, or call the function registered by the developer on the App.
Add global properties to app.js file

//全局属性,所有页面都可以访问
globalData:{
    
    
  userInfo:"我是全局可访问的数据"
}

We read global properties in info.js file

// pages/info/info.js
Page({
    
    

  /**
   * 页面的初始数据
   */
  data: {
    
    
    message:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
    
    const appInstance= getApp()
    this.setData({
    
    message:appInstance.globalData.userInfo})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
    

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    
    

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    
    

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    
    

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    
    

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    
    

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    
    

  }
})

Modify the display content of the info.wxml file

<text>{
   
   {message}}</text>

Display of results:
insert image description here

1.2, page configuration

1.2.1, the life cycle function of the page

Register a page in the applet. Specify the lifecycle function of the page
insert image description here

Attributes type illustrate
onLoad function Lifecycle callbacks - listen for page loads
onShow function Lifecycle callback - monitor page display
onReady function Lifecycle callback - monitor the completion of the initial rendering of the page
onHide function Lifecycle callback - monitor page hide
onUnload function Lifecycle callback - listen for page unloading

Add the following in info.js:

// pages/info/info.js
Page({
    
    

  /**
   * 页面的初始数据
   */
  data: {
    
    
    message:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
    
    console.log("页面加载");
    const appInstance= getApp()
    this.setData({
    
    message:appInstance.globalData.userInfo})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
    
    console.log("页面渲染完成");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    
    
    console.log("页面显示");
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    
    
    console.log("页面隐藏");
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    
    
    console.log("页面卸载");
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    
    
    console.log("下拉动作");
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    
    
    console.log("页面上拉触底事件");
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    
    
    console.log("用户点击右上角分享");
  }
})

Display of results:
insert image description here

The role of life cycle functions

In different life cycle functions, business can be added according to business needs. For example: we can modify the data in data in the onShow function

Page({
    
    
  data:{
    
    
    hello:"hello"
   },
  onShow() {
    
    
    this.setData({
    
    
      hello:"大家好,我是初学小程序的人"
     })
   }
})

Finally: It is recommended that you remember these life cycles of the applet! ! ! ! !

1.2.2, the Data object of the page

  • A simple understanding is that the back-end data is displayed in the front-end, usually through this data object, which is the initial data used for the first rendering of the page.
  • When the page is loaded, the data in data will be transmitted from the logic layer to the rendering layer in the form of JSON strings, so the data in data must be of a type that can be converted to JSON: strings, numbers, booleans, objects, arrays

The example is as follows:
Add the following configuration to info.js

// pages/info/info.js
Page({
    
    

  /**
   * 页面的初始数据
   */
  data: {
    
    
    hello: "hello world",
    num: 1,
    flag: true,
    user: {
    
    
      name: "zhz",
      age: 19
    },
    names: ["zhz", "xiaobai", "zhz小白"]
  }
})

add in info.wxml

<view><text>{
   
   { hello }}</text></view>
<view><text>{
   
   { num }}</text></view>
<view><text>{
   
   { flag }}</text></view>
<view><text>{
   
   { user.name }}</text></view>
<view><text>{
   
   { names[1] }}</text></view>

Display of results:
insert image description here

If we want to modify the value in the data object, we can write:

// pages/info/info.js
Page({
    
    

  /**
   * 页面的初始数据
   */
  data: {
    
    
    hello: "hello world",
    num: 1,
    flag: true,
    user: {
    
    
      name: "zhz",
      age: 19
    },
    names: ["zhz", "xiaobai", "zhz小白"]
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
    
    this.setData({
    
    
      flag:false,
      num:2
    })
})

The display effect is as follows: we found that the flag and num have been changed
insert image description here

I am zhz Xiaobai, a novice in the Internet industry, determined to become an architect
https://blog.csdn.net/zhouhengzhe?t=1

Guess you like

Origin blog.csdn.net/zhouhengzhe/article/details/126870711