# Weixin Mini Program Code composition

​ In the previous chapter, we quickly created a QuickStart project using developer tools. You can notice that different types of files are generated in this project:

  1. .JsonSuffixJSONConfiguration file
  2. ..WxmlSuffixWXMLtemplate file
  3. ..WXSS``WXSSstyle file
  4. .JSsuffixJSscript logic file

Next we look at the role of each of these four types of documents.

# JSON configuration

JSON is a data format, not a programming language. In Weixin Mini Program, JSON plays the role of static configuration.

We can see that in the root directory of the project there is a apagejsonandproject.config.json, in addition to thepages / logsdirectorylogs.json, let's go through their use.

# Weixin Mini Program Configure apagejson

Apagejsonis the global configuration of the current Weixin Mini Program, including all page paths of the Mini Program, interface performance, network timeout, bottom tab, etc.Theapagejsonconfiguration in QuickStart is as follows:

{
  "pages":[
    "pages/index/index",
    "pages/logs/logs"
  ],
  "window":{
    "backgroundTextStyle":"light",
    "navigationBarBackgroundColor": "#fff",
    "navigationBarTitleText": "Weixin",
    "navigationBarTextStyle":"black"
  }
}

Let's briefly say what this configuration item means:

  1. Pagesfield - describes all the current Weixin Mini Program page paths, so that the WeChat client knows which directory your Mini Program page is defined in.
  2. WindowField -- Defines Weixin Mini Program top background color for all pages, text color definition, etc.

Additional configuration details can be found in the document Weixin Mini Program Configuration apagejson .

# Tool Configuration project.config.json

Usually, when you use a tool, you personalize it for your preferences, such as the color of the interface, the compilation configuration, and so on. When you reinstall the tool on another computer, you also reconfigure it.

With this in mind, the Weixin Mini Program developer tool generates a [[] in the root directory of each projectproject.config.json. Any configuration you make on the tool will be written to this file. When you reinstall the tool or change your computer to work,As soon as you load a code bundle for the same project, the developer tools automatically return you to the personalized configuration you had when you were developing the project, including options such as the color of the editor, automatic compression of the code when uploaded, and so on.

Additional configuration details can be found in the documentation Developer Tools Configuration .

# Page configuration page.json

Here,page.jsonis actually used to representlogs.jsonconfigurations related to Weixin Mini Program pages in the pages / logs directory.

If your entire Weixin Mini Program style is blue, then you can declare that the top color is blue in theapagejson.This may not be the case, because each page in your Mini Program might have a different color to distinguish between different functional modules, so we providepage.json,This allows developers to define some of the properties of each page independently, such as the top color, whether a drop-down refresh is allowed, and so on.

Additional configuration details can be found in the page configuration documentation.

# JSON syntax

Here are some notes about JSON configuration in Weixin Mini Program.

JSON files are all wrapped in a braces {}, and the data is expressed by key-value.A JSON key must be wrapped in a double quotation mark, and in practice, it is a common mistake when writing JSON to forget to put double quotation marks on the key value or write double quotation marks as single quotation marks.

JSON can only be in one of the following data formats; any other format will trigger errors, such as undefined in JavaScript.

  1. Numbers, including floating-point numbers and integers
  2. Character string, enclosed in double quotes.
  3. Bool value, true or false
  4. Arrays that need to be wrapped in square brackets []
  5. Objects need to be enclosed in parentheses {}
  6. Null

It is also important to note that comments are not available in JSON files, and attempts to add comments will cause an error.

# WXML templates

People who have done web programming know that web programming uses a combination of HTML + CSS + JS, whereHTMLIt is used to describe the current structure of the page,CSSdescribes what the page looks like, andJSis usually used to handle the interaction between the page and the user.

Similarly, the same role exists in Weixin Mini Program, whereWXMLacts likeHTML.Openpages / index / index.wxmland you will see the following:

<view class="container">
  <view class="userinfo">
    <button wx:if="{{!hasUserInfo && canIUse}}"> 获取头像昵称 </button>
    <block wx:else>
      <image src="{{userInfo.avatarUrl}}" background-size="cover"></image>
      <text class="userinfo-nickname">{{userInfo.nickName}}</text>
    </block>
  </view>
  <view class="usermotto">
    <text class="user-motto">{{motto}}</text>
  </view>
</view>

Much likeHTML,WXMLconsists of tags, attributes, and so on.But there are a lot of differences, and let's explain them all:

  1. The label name is a little different

    When writing HTML, the most frequently used tag isdiv,p,span,When a developer writes a page, they can combine different components based on these basic tags, such as calendars, pop-ups, and so on. To put it another way, since everyone needs these components, why can't we package these commonly used components to greatly improve our development efficiency?

    As you can see from the above example, the Weixin Mini ProgramWXMLuses the tag [[ TAG-1-START]] view,button,text`Wait, these tags are the basic capabilities that the Mini Programs package for developers, and we also provide maps, video, audio, and other component capabilities.

    More detailed components are described in the next section Weixin Mini Program

  2. More properties likewx: ifand expressions like {{}}

    In the general web development process, we usually use theJSto manipulate theDOM(Corresponding toHTMLdescription generated tree) to cause some changes in the interface in response to user behavior.For example, when a user clicks a button,JSrecords some state to theJSvariable, along with`` DOMAPI manipulates the properties or behavior of theDOM [()], causing some interface changes.As your project gets bigger, your code is filled with a lot of interface interaction logic and various state variables of the program. Clearly this is not a good development model, so there are MVVM development models (e.g. React, Vue) that advocate separation of rendering and logic.Simply put, don't letJSdirectly controlDOMJS`You just need to manage the state, and then describe the relationship between the state and the interface structure through a templating syntax.

    Weixin Mini Program framework also uses this idea, if you need to put aHello WorldThe character string of the.

    WXML says this:

    <text>{{msg}}</text>
    

    JS 只需要管理状态即可:

    this.setData({ msg: "Hello World" })
    

    通过 {{ }} 的语法把一个变量绑定到界面上,我们称为数据绑定。仅仅通过数据绑定还不够完整的描述状态和界面的关系,还需要 if/else, for等控制能力,在小程序里边,这些控制能力都用 wx: 开头的属性来表达。

更详细的文档可以参考 WXML

# WXSS 样式

WXSS 具有 CSS 大部分的特性,小程序在 WXSS 也做了一些扩充和修改。

  1. 新增了尺寸单位。在写 CSS 样式时,开发者需要考虑到手机设备的屏幕会有不同的宽度和设备像素比,采用一些技巧来换算一些像素单位。WXSS 在底层支持新的尺寸单位 rpx ,开发者可以免去换算的烦恼,只要交给小程序底层来换算即可,由于换算采用的浮点数运算,所以运算结果会和预期结果有一点点偏差。

  2. 提供了全局的样式和局部样式。和前边 app.json, page.json 的概念相同,你可以写一个 app.wxss 作为全局样式,会作用于当前小程序的所有页面,局部页面样式 page.wxss 仅对当前页面生效。

  3. 此外 WXSS 仅支持部分 CSS 选择器

更详细的文档可以参考 WXSS

# JS 逻辑交互

一个服务仅仅只有界面展示是不够的,还需要和用户做交互:响应用户的点击、获取用户的位置等等。在小程序里边,我们就通过编写 JS 脚本文件来处理用户的操作。

{{ msg }}
 <button bindtap="clickMe">Click on me</button> 

点击 button 按钮的时候,我们希望把界面上 msg 显示成 "Hello World",于是我们在 button 上声明一个属性: bindtap ,在 JS 文件里边声明了 clickMe 方法来响应这次点击操作:

Page({
  clickMe: function() {
    this.setData({ msg: "Hello World" })
  }
})

响应用户的操作就是这么简单,更详细的事件可以参考文档 WXML - 事件

此外你还可以在 JS 中调用小程序提供的丰富的 API,利用这些 API 可以很方便的调起微信提供的能力,例如获取用户信息、本地存储、微信支付等。在前边的 QuickStart 例子中,在 pages/index/index.js 就调用了 wx.getUserInfo 获取微信用户的头像和昵称,最后通过 setData 把获取到的信息显示到界面上。更多 API 可以参考文档 小程序的API

通过这个章节,你了解了小程序涉及到的文件类型以及对应的角色,在下个章节中,我们把这一章所涉及到的文件通过 “小程序的框架” 给 “串” 起来,让他们都工作起来。