Getting Started with WeChat Mini Programs

Mini Program Directory Structure

An applet consists of an app that describes the overall program and multiple pages that describe their respective pages.

The main part of a small program consists of three files, which must be placed in the root directory of the project, as follows:

file required
app.js is the applet logic
app.json is the applet public settings
app.wxss No Mini Program public style sheet

An applet page consists of four files, namely:

file type required role
js is the page logic
wxml is the page structure
wxss no page style sheet
json No page configuration

Note: In order to facilitate developers to reduce configuration items, we stipulate that the four files of the description page must have the same path and file name

Configure
the app.json file to configure the WeChat applet globally, determine the path of the page file, window performance, set the network timeout, set multiple tabs, etc.

Here is a simple configuration app.json with all configuration options:

 

{
  "pages": [
    "pages/index/index",
    "pages/logs/index"
  ],
  "window": {
    "navigationBarTitleText": "Demo"
  },
  "tabBar": {
    "list": [{
      "pagePath": "pages/index/index",
      "text": "首页"
    }, {
      "pagePath": "pages/logs/logs",
      "text": "日志"
    }]
  },
  "networkTimeout": {
    "request": 10000,
    "downloadFile": 10000
  },
  "debug": true
}

app.json list of configuration items

Property Type Required Description
pages StringArray is to set the page path
window Object No Set the window performance of the default page
tabBar Object No Set the performance of the bottom tab
networkTimeout Object No Set the network timeout time
debug Boolean No Set whether to enable debug mode

pages

Accepts an array, each item is a string, to specify which pages the applet consists of. Each item represents the [path + file name] information of the corresponding page, and the first item of the array represents the initial page of the applet. To add/remove pages in the applet, you need to modify the pages array.

The file name does not need to write a file suffix, because the framework will automatically find the four files of the path .json, .js, .wxml, and .wxss for integration.

For example, the development directory is:

pages/

pages/index/index.wxml

pages/index/index.js

pages/index/index.wxss

pages/logs/logs.wxml

pages/logs/logs.js

app.js

app.json

app.wxss

则,我们需要在 app.json 中写

{
  "pages":[
    "pages/index/index"
    "pages/logs/logs"
  ]
}

window

用于设置小程序的状态栏、导航条、标题、窗口背景色。

navigationBarBackgroundColor 	   HexColor   #000000 	  导航栏背景颜色,如"#000000"
navigationBarTextStyle 	           String     white 	  导航栏标题颜色,仅支持 black/white
navigationBarTitleText 	           String                  导航栏标题文字内容
backgroundColor 	           HexColor   #ffffff 	   窗口的背景色
backgroundTextStyle 	           String 	dark 	    下拉背景字体、loading 图的样式,仅支持 dark/light
enablePullDownRefresh 	          Booleanfalse              是否开启下拉刷新

注:HexColor(十六进制颜色值),如"#ff00ff"

如 app.json :

{
  "window":{
    "navigationBarBackgroundColor": "#ffffff",
    "navigationBarTextStyle": "black",
    "navigationBarTitleText": "微信演示",
    "backgroundColor": "#eeeeee",
    "backgroundTextStyle": "light"
  }
}

tabBar

如果我们的小程序是一个多 tab 应用(客户端窗口的底部或顶部有 tab 栏可以切换页面),那么我们可以通过 tabBar 配置项指定 tab 栏的表现,以及 tab 切换时显示的对应页面。

Tip: 通过页面跳转(wx.navigateTo)或者页面重定向(wx.redirectTo)所到达的页面,即使它是定义在 tabBar 配置中的页面,也不会显示底部的 tab 栏。

tabBar 是一个数组,只能配置最少2个、最多5个 tab,tab 按数组的顺序排序。

属性说明:

属性             类型            必填        默认值               描述
color           HexColor         是 		               tab 上的文字默认颜色
selectedColor 	HexColor         是 		               tab 上的文字选中时的颜色
backgroundColor HexColor         是 		               tab 的背景色
borderStyle 	String           否 	    black 	       tabbar上边框的颜色,仅支持 black/white
list            Array            是 		               tab 的列表,详见 list 属性说明,最少2个、最多5个 tab
position 	String           否 	    bottom 	       可选值 bottom、top

其中 list 接受一个数组,数组中的每个项都是一个对象,其属性值如下:

属性                 类型                  必填      说明
pagePath 	    String                 是        页面路径,必须在 pages 中先定义
text 	            String                 是 	     tab 上按钮文字
iconPath 	    String                 是        图片路径,icon 大小限制为40kb
selectedIconPath    String                 是        选中时的图片路径,icon 大小限制为40kb

networkTimeout

设置各种网络请求的超时时间。

属性说明:

属性             类型             必填            说明
request 	Number            否 	          wx.request的超时时间,单位毫秒,默认为:60000
connectSocket 	Number            否 	          wx.connectSocket的超时时间,单位毫秒,默认为:60000
uploadFile 	Number            否 	          wx.uploadFile的超时时间,单位毫秒,默认为:60000
downloadFile 	Number            否 	          wx.downloadFile的超时时间,单位毫秒,默认为:60000

page.json

每一个小程序页面也可以使用.json文件来对本页面的窗口表现进行配置。 页面的配置比app.json全局配置简单得多,只是设置 app.json 中的 window 配置项的内容,页面中配置项会覆盖 app.json 的 window 中相同的配置项。

页面的.json只能设置 window 相关的配置项,以决定本页面的窗口表现,所以无需写 window 这个键,如:

属性类型默认值描述
navigationBarBackgroundColor 	HexColor         #000000 	导航栏背景颜色,如"#000000"
navigationBarTextStyle 	        String 	        white 	        导航栏标题颜色,仅支持 black/white
navigationBarTitleText 	        String                          导航栏标题文字内容
backgroundColor 	        HexColor        #ffffff 	窗口的背景色
backgroundTextStyle 	        String 	        dark 	        下拉背景字体、loading 图的样式,仅支持 dark/light
enablePullDownRefresh 	        Boolean         false            是否开启下拉刷新,详见页面相关事件处理函数。
disableScroll 	                Boolean         false            设置为true则页面整体不能上下滚动;只在 page.json 中有效,无法在 app.json 中设置该项

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

 底部导航修改步骤

1、制作图标并保存到项目(在项目下创建imgs文件夹保存图标文件)

|_ imgs
    |_ icon_1.png
    |_ icon_2.png

2、修改app.json

{
  "pages":[
    "pages/index/index",
    "pages/logs/logs"
  ],
  "window":{
    "backgroundTextStyle":"light",
    "navigationBarBackgroundColor": "#fff",
    "navigationBarTitleText": "WeChat",
    "navigationBarTextStyle":"black"
  },
  "tabBar": {
    "list": [{
      "pagePath": "pages/index/index",
      "text": "首页",
      "iconPath": "imgs/icon_1.png",
      "selectedIconPath": "imgs/icon_1.png"
    }, {
      "pagePath": "pages/logs/logs",
      "text": "日志",
      "iconPath": "imgs/icon_2.png",
      "selectedIconPath": "imgs/icon_2.png"
    }]
  }
}

 Registration procedure App()

The App() function is used to register an applet. Accepts an object parameter, which specifies the life cycle function of the applet, etc.
object parameter description:

 Attribute Type Description Trigger Timing

onLaunch Function life cycle function -- monitoring applet initialization When the applet initialization is completed, onLaunch will be triggered (only triggered once globally)
onShow Function life cycle function - monitor applet display When the applet starts, or enters the foreground display from the background, onShow will be triggered
onHide Function life cycle function--listen to the applet hiding When the applet enters the background from the foreground, onHide will be triggered
onError Function Error monitoring function When a script error occurs in the applet, or the api call fails, it will trigger onError and bring the error message. Other Any developers can add any function or data to the Object parameter, which can be accessed with this

 Definition of foreground and background: When the user clicks the upper left corner to close, or presses the home button of the device to leave WeChat, the applet is not directly destroyed, but enters the background; when the user enters WeChat again or opens the applet again, it will enter the foreground from the background again .

Only when the applet enters the background for a certain period of time, or the system resource usage is too high, it will be really destroyed.

 Example:

App({
  onLaunch: function() {
    // Do something initial when launch.
  },
  onShow: function() {      // Do something when show.
  },
  onHide: function() {      // Do something when hide.
  },
  onError: function(msg) {    console.log(msg)
  },
  globalData: 'I am global data'
})

 getApp()

The applet provides the global getApp() function to get the applet instance.
// other.js
var appInstance = getApp ()
console.log(appInstance.globalData) // I am global data

 Notice:

App() must be registered in app.js and cannot be registered more than one.
Don't call getApp() in a function defined in App(), use this to get the app instance.
Do not call getCurrentPage() during onLaunch, when the page has not been generated.
After obtaining the instance through getApp(), do not call the lifecycle function privately.

 Registration page Page()

The Page() function is used to register a page. Accepts an object parameter, which specifies the initial data of the page, life cycle function, event handler, etc.
object parameter description:
property type description
data Object The initial data of the page    
onLoad Function life cycle function--listen to page load    
onReady Function life cycle function--listen to the completion of the initial rendering of the page
onShow Function life cycle function -- monitor page display    
onHide Function life cycle function--listen to page hiding
onUnload Function life cycle function--listen to page unloading
onPullDownRefresh Function Page-related event handlers--listen to user pull-down actions    
onReachBottom Function The handler for the bottom-up event on the page    
onShareAppMessage  Function               用户点击右上角分享其他Any开发者可以添加任意的函数或数据到object参数中,在页面的函数中用this可以访问

初始化数据

初始化数据将作为页面的第一次渲染。data 将会以 JSON 的形式由逻辑层传至渲染层,所以其数据必须是可以转成 JSON 的格式:字符串,数字,布尔值,对象,数组。
渲染层可以通过 WXML 对数据进行绑定。
示例代码:

<view>{{text}}</view>
<view>{{array[0].msg}}</view>
Page({
  data: {
    text: 'init data',
    array: [{msg: '1'}, {msg: '2'}]
  }
})

 生命周期函数说明

onLoad: page load
A page will only be called once.
Receiving page parameters can get wx.navigateTo and wx.redirectTo and query in <navigator/>.

onShow: The page is displayed. It will be called once
every time the page is opened.

onReady: The initial rendering of the page is completed.
A page will only be called once, which means that the page is ready to interact with the view layer.
For interface settings such as wx.setNavigationBarTitle, please set it after onReady. See life cycle

onHide: page hide Called
when navigateTo or bottom tab is switched.

onUnload: The page is unloaded
when redirectTo or navigateBack is called.
Page-related event handler

onPullDownRefresh: Pull down to refresh
Listen for user pull down to refresh events.
You need to enable enablePullDownRefresh in the window options of config.
When the data refresh is processed, wx.stopPullDownRefresh can stop the pull-down refresh of the current page.

onShareAppMessage: User sharing
Only if this event handler is defined, the "Share" button will be displayed in the upper right corner menu
. When the user clicks the share button, it will be called
. This event needs to return an Object, which is used to customize the sharing content.
Sharing settings demonstration
Page({
  ......,
  onShareAppMessage: function () {
    return {
      title: 'Custom share title',
      desc: 'Custom share description',
      path: '/page/user?id=123'
    }
  }
})

 

Event handlers
In addition to initializing data and life cycle functions, Page can also define some special functions: event handlers. In the rendering layer, event binding can be added to the component. When the trigger event is reached, the event handler defined in the Page will be executed.
Sample code:

<view bindtap="viewTap"> click me </view>
Page({
  viewTap: function() {
    wx.showToast({title:'hi'});
  }
})

 Page.prototype.setData()

The setData function is used to send data from the logic layer to the view layer, while changing the value of the corresponding this.data.
Note:
Modifying this.data directly is invalid, cannot change the state of the page, and will cause data inconsistency.
The data set at one time cannot exceed 1024kB, please try to avoid setting too much data at one time.
setData() parameter format
Accepts an object in the form of key and value to change the value corresponding to key in this.data to value.
The key can be very flexible, given in the form of data path, such as array[2].message, abcd, and does not need to be pre-defined in this.data.

Sample code:
Page({
    data:{
        "text1":"hi"
    },
    myfunc : function(){
        //wx.showToast({title:'hi'});
        this.setData({"text1":"hi......"});
    }
});

 页面跳转

wx.navigateTo({
    url: "../logs/logs"
})

文件作用域
在 JavaScript 文件中声明的变量和函数只在该文件中有效;不同的文件中可以声明相同名字的变量和函数,不会互相影响。
通过全局函数 getApp() 可以获取全局的应用实例,如果需要全局的数据可以在 App() 中设置,如:

// app.js
App({
  globalData:{
    appName :'hcoder'
  }
})
// page.js
var app = getApp();
Page({
    data:{},
    myfunc : function(){
        //wx.showToast({title:'hi'});
        this.setData({"text1":"hi......"});
    },
    onLoad: function(){
        this.setData({'appName':app.globalData.appName});
    }
});

模块化(js引用)
我们可以将一些公共的代码抽离成为一个单独的 js 文件,作为一个模块。模块只有通过 module.exports 或者 exports 才能对外暴露接口。
需要注意的是:
exports 是 module.exports 的一个引用,因此在模块里边随意更改 exports 的指向会造成未知的错误。所以我们更推荐开发者采用 module.exports 来暴露模块接口,除非你已经清晰知道这两者的关系。

示例 : 

//common.js
function toast(msg){
    wx.showToast({title:msg});
}
module.exports.toast = toast;
//页面调用
var app = getApp();
var common = require('../../common.js');
Page({
    data:{
    },
    myfunc : function(){
        common.toast('ok');
        this.setData({"text1":"hi......"});
    },
    onLoad: function(){
        this.setData({'appName':app.globalData.appName});
    }
});

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326392387&siteId=291194637