Python - 微信小程序(框架)

小程序配置

  • 全局配置

    • 简介
      小程序根目录下的 app.json 文件用来对微信小程序进行全局配置。文件内容为一个 JSON 对象,有以下属性
    • 配置项
      属性 类型 必填 描述 最低版本
      entryPagePath string 小程序默认启动首页
      pages string[] 页面路径列表
      window Object 全局的默认窗口表现
      tabBar Object 底部 tab 栏的表现
      networkTimeout Object 网络超时时间
      debug boolean 是否开启 debug 模式,默认关闭
      functionalPages boolean 是否启用插件功能页,默认关闭 2.1.0
      subpackages Object[] 分包结构配置 1.7.3
      workers string Worker 代码放置的目录 1.9.90
      requiredBackgroundModes string[] 需要在后台使用的能力,如「音乐播放」
      plugins Object 使用到的插件 1.9.6
      preloadRule Object 分包预下载规则 2.3.0
      resizable boolean PC 小程序是否支持用户任意改变窗口大小(包括最大化窗口);iPad 小程序是否支持屏幕旋转。默认关闭 2.3.0
      usingComponents Object 全局自定义组件配置 开发者工具 1.02.1810190
      permission Object 小程序接口权限相关设置 微信客户端 7.0.0
      sitemapLocation string 指明 sitemap.json 的位置
      style string 指定使用升级后的 weui 样式 2.8.0
      useExtendedLib Object 指定需要引用的扩展库 2.2.1
      entranceDeclare Object 微信消息用小程序打开 微信客户端 7.0.9
      darkmode boolean 小程序支持 DarkMode 2.11.0
      themeLocation string 指明 theme.json 的位置,darkmode 为 true 为必填 开发者工具 1.03.2004271
      lazyCodeLoading string 配置自定义组件代码按需注入 2.11.1
      singlePage Object 单页模式相关配置 2.12.0
      supportedMaterials Object 聊天素材小程序打开相关配置 2.14.3
      serviceProviderTicket string 定制化型服务商票据
      embeddedAppIdList string[] 内嵌小程序 appId
    • pages
      • 简介
        • 用于指定小程序由哪些页面组成,每一项都对应一个页面的 路径(含文件名) 信息。文件名不需要写文件后缀,框架会自动去寻找对应位置的 .json, .js, .wxml, .wxss 四个文件进行处理。
        • 未指定 entryPagePath 时,数组的第一项代表小程序的初始页面(首页)。
        • 小程序中新增 / 减少页面,都需要对 pages 数组进行修改。
      • 示例
        1
        2
        3
        4
        5
        6
        // pages
        "pages": [
        "pages/index/index",
        "pages/logs/logs",
        "pages/home/home"
        ],
    • window
      • 简介
        用于设置小程序的状态栏、导航条、标题、窗口背景色。
      • 参数
        属性 类型 默认值 描述 最低版本
        navigationBarBackgroundColor HexColor #000000 导航栏背景颜色,如 #000000
        navigationBarTextStyle string white 导航栏标题颜色,仅支持 black / white
        navigationBarTitleText string 导航栏标题文字内容
        navigationStyle string default 导航栏样式,仅支持以下值: default 默认样式 custom 自定义导航栏,只保留右上角胶囊按钮。参见注 2。 iOS/Android 微信客户端 6.6.0,Windows 微信客户端不支持
        backgroundColor HexColor #ffffff 窗口的背景色
        backgroundTextStyle string dark 下拉 loading 的样式,仅支持 dark / light
        backgroundColorTop string #ffffff 顶部窗口的背景色,仅 iOS 支持 微信客户端 6.5.16
        backgroundColorBottom string #ffffff 底部窗口的背景色,仅 iOS 支持 微信客户端 6.5.16
        enablePullDownRefresh boolean false 是否开启全局的下拉刷新。 详见 Page.onPullDownRefresh
        onReachBottomDistance number 50 页面上拉触底事件触发时距页面底部距离,单位为 px。 详见 Page.onReachBottom
        pageOrientation string portrait 屏幕旋转设置,支持 auto / portrait / landscape 详见 响应显示区域变化 2.4.0 (auto) / 2.5.0 (landscape)
        restartStrategy string homePage 重新启动策略配置 2.8.0
        initialRenderingCache string 页面初始渲染缓存配置,支持 static / dynamic 2.11.1
        visualEffectInBackground string none 切入系统后台时,隐藏页面内容,保护用户隐私。支持 hidden / none 2.15.0
      • 注意
        • HexColor(十六进制颜色值),如 "#ff00ff"
        • 关于 navigationStyle
          • iOS/Android 客户端 7.0.0 以下版本,navigationStyle 只在 app.json 中生效。
          • iOS/Android 客户端 6.7.2 版本开始,navigationStyle: customweb-view 组件无效
          • 开启 custom 后,低版本客户端需要做好兼容。开发者工具基础库版本切到 1.7.0(不代表最低版本,只供调试用)可方便切到旧视觉
          • Windows 客户端 3.0 及以上版本,为了给用户提供更符合桌面软件的使用体验,统一了小程序窗口的导航栏,navigationStyle: custom 不再生效
      • 示例
        1
        2
        3
        4
        5
        6
        7
        // window
        "window": {
        "backgroundTextStyle": "light",
        "navigationBarBackgroundColor": "#0dcaf0",
        "navigationBarTitleText": "苏寅 Applet",
        "navigationBarTextStyle": "black"
        },
      • 效果图
        window
    • tabBar
      • 简介
        如果小程序是一个多 tab 应用(客户端窗口的底部或顶部有 tab 栏可以切换页面),可以通过 tabBar 配置项指定 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 tabBar 的位置,仅支持 bottom / top
        custom boolean false 自定义 tabBar,见详情 2.5.0
        • 其中 list 接受一个数组,只能配置最少 2 个、最多 5 个 tab。tab 按数组的顺序排序,每个项都是一个对象,其属性值如下
          属性 类型 必填 说明
          pagePath string 页面路径,必须在 pages 中先定义
          text string tab 上按钮文字
          iconPath string 图片路径,icon 大小限制为 40kb,建议尺寸为 81px * 81px,不支持网络图片。 positiontop 时,不显示 icon。
          selectedIconPath string 选中时的图片路径,icon 大小限制为 40kb,建议尺寸为 81px * 81px,不支持网络图片。 positiontop 时,不显示 icon。
      • 示例
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        // tabBar
        "tabBar": {
        "selectedColor": "#dc3545",
        "list": [{
        "pagePath": "pages/index/index",
        "text": "首页",
        "iconPath": "/static/images/icon/index.png",
        "selectedIconPath": "/static/images/icon/index_s.png"
        },
        {
        "pagePath": "pages/home/home",
        "text": "主页",
        "iconPath": "/static/images/icon/home.png",
        "selectedIconPath": "/static/images/icon/家.png"
        },
        {
        "pagePath": "pages/logs/logs",
        "text": "日志",
        "iconPath": "/static/images/icon/log.png",
        "selectedIconPath": "/static/images/icon/log_s.png"
        }
        ]
        },
      • 效果图
        tabBar
      • 图标下载地址:阿里巴巴矢量图标库
  • 页面配置

    • 简介
      每一个小程序页面也可以使用 .json 文件来对本页面的窗口表现进行配置。页面中配置项在当前页面会覆盖 app.jsonwindow 中相同的配置项。文件内容为一个 JSON 对象,有以下属性
    • 配置项
      属性 类型 默认值 描述 最低版本
      navigationBarBackgroundColor HexColor #000000 导航栏背景颜色,如 #000000
      navigationBarTextStyle string white 导航栏标题颜色,仅支持 black / white
      navigationBarTitleText string 导航栏标题文字内容
      navigationStyle string default 导航栏样式,仅支持以下值: default 默认样式 custom 自定义导航栏,只保留右上角胶囊按钮。参见注 1。 iOS/Android 微信客户端 7.0.0,Windows 微信客户端不支持
      backgroundColor HexColor #ffffff 窗口的背景色
      backgroundTextStyle string dark 下拉 loading 的样式,仅支持 dark / light
      backgroundColorTop string #ffffff 顶部窗口的背景色,仅 iOS 支持 微信客户端 6.5.16
      backgroundColorBottom string #ffffff 底部窗口的背景色,仅 iOS 支持 微信客户端 6.5.16
      enablePullDownRefresh boolean false 是否开启当前页面下拉刷新。 详见 Page.onPullDownRefresh
      onReachBottomDistance number 50 页面上拉触底事件触发时距页面底部距离,单位为 px。 详见 Page.onReachBottom
      pageOrientation string portrait 屏幕旋转设置,支持 auto / portrait / landscape 详见 响应显示区域变化 2.4.0 (auto) / 2.5.0 (landscape)
      disableScroll boolean false 设置为 true 则页面整体不能上下滚动。 只在页面配置中有效,无法在 app.json 中设置
      usingComponents Object 页面自定义组件配置 1.6.3
      initialRenderingCache string 页面初始渲染缓存配置,支持 static / dynamic 2.11.1
      style string default 启用新版的组件样式 2.10.2
      singlePage Object 单页模式相关配置 2.12.0
      restartStrategy string homePage 重新启动策略配置 2.8.0

框架接口

  • 页面

    • Page
      • 简介
        注册小程序中的一个页面。接受一个 Object 类型参数,其指定页面的初始数据、生命周期回调、事件处理函数等。
      • 参数
        属性 类型 默认值 必填 说明
        data Object 页面的初始数据
        options Object 页面的组件选项,同 Component 构造器 中的 options ,需要基础库版本 2.10.1
        onLoad function 生命周期回调 — 监听页面加载
        onShow function 生命周期回调 — 监听页面显示
        onReady function 生命周期回调 — 监听页面初次渲染完成
        onHide function 生命周期回调 — 监听页面隐藏
        onUnload function 生命周期回调 — 监听页面卸载
        onPullDownRefresh function 监听用户下拉动作
        onReachBottom function 页面上拉触底事件的处理函数
        onShareAppMessage function 用户点击右上角转发
        onShareTimeline function 用户点击右上角转发到朋友圈
        onAddToFavorites function 用户点击右上角收藏
        onPageScroll function 页面滚动触发事件的处理函数
        onResize function 页面尺寸改变时触发,详见 响应显示区域变化
        onTabItemTap function 当前是 tab 页时,点击 tab 时触发
        onSaveExitState function 页面销毁前保留状态回调
        其他 any 开发者可以添加任意的函数或数据到 Object 参数中,在页面的函数中用 this 可以访问
    • getCurrentPages
      • 简介
        获取当前页面栈。数组中第一个元素为首页,最后一个元素为当前页面。
      • 注意事项
        • 不要尝试修改页面栈,会导致路由以及页面状态错误。
        • 不要在 App.onLaunch 的时候调用 getCurrentPages(),此时 page 还没有生成。
  • 基础功能

    • console
      • 简介
        向调试面板中打印日志。console 是一个全局对象,可以直接访问。在微信客户端中,向 vConsole 中输出日志。
      • 方法
        名称 说明
        console.debug() 向调试面板中打印 debug 日志
        console.log() 向调试面板中打印 log 日志
        console.info() 向调试面板中打印 info 日志
        console.warn() 向调试面板中打印 warn 日志
        console.error() 向调试面板中打印 error 日志
    • 定时器
      • setTimeout
        • 简介
          设定一个定时器。在定时到期以后执行注册的回调函数。

        • 参数

          名称 说明
          function callback 回调函数
          number delay 延迟的时间,函数的调用会在该延迟之后发生,单位 ms。
          any rest param1, param2, ..., paramN 等附加参数,它们会作为参数传递给回调函数。
        • 返回值

          名称 说明
          number 定时器的编号。这个值可以传递给 clearTimeout 来取消该定时。
      • clearTimeout
        • 简介
          取消由 setTimeout 设置的定时器。
        • 参数
          名称 说明
          number timeoutID 要取消的定时器的 ID
      • setInterval
        • 简介
          设定一个定时器。按照指定的周期(以毫秒计)来执行注册的回调函数。
        • 参数
          名称 说明
          function callback 回调函数
          number delay 执行回调函数之间的时间间隔,单位 ms。
          any rest param1, param2, ..., paramN 等附加参数,它们会作为参数传递给回调函数。
        • 返回值
          名称 说明
          number 定时器的编号。这个值可以传递给 clearInterval 来取消该定时。
      • clearInterval
        • 简介
          取消由 setInterval 设置的定时器。
        • 参数
          名称 说明
          number intervalID 要取消的定时器的 ID

WXML 语法参考

  • 介绍

    • WXML(WeiXin Markup Language)是框架设计的一套标签语言,结合基础组件事件系统,可以构建出页面的结构。
    • 用以下一些简单的例子来看看 WXML 具有什么能力
  • 数据绑定

    • 简介
      WXML 中的动态数据均来自对应 Page 的 data。
    • 简单绑定
      数据绑定使用 Mustache 语法(双大括号)将变量包起来
    • 示例
      1
      2
      3
      <!-- bind.wxml -->
      <view>数据1:{{message}}</view>
      <view>数据2:{{message}}</view>
      1
      2
      3
      4
      5
      6
      // bind.js
      Page({
      data: {
      message: "苏寅教程"
      },
      })
    • 数据更新
      1
      2
      3
      4
      5
      <!-- bind.wxml -->
      <view>数据1:{{message}}</view>
      <view>数据2:{{message}}</view>

      <button bindtap="changeData">点击修改数据</button>
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      // bind.js
      Page({
      ......
      data: {
      message: "苏寅教程"
      },

      changeData: function () {
      // 获取数据
      console.log(this.data.message);
      // 修改数据(错误,只改后端)
      // this.data.message = '天下无双';
      // console.log(this.data.message);
      // 修改数据
      this.setData({
      message: '天下无双'
      });
      },
      })
  • 列表渲染

    • wx:for
      • 简介
        • 在组件上使用 wx:for 控制属性绑定一个数组,即可使用数组中各项的数据重复渲染该组件。
        • 默认数组的当前项的下标变量名默认为 index,数组当前项的变量名默认为 item
        • 使用 wx:for-item 可以指定数组当前元素的变量名
        • 使用 wx:for-index 可以指定数组当前下标的变量名
      • 示例
        1
        2
        3
        4
        5
        6
        // goods.js
        Page({
        data: {
        dataList: ['苹果', '香蕉', '西瓜']
        },
        )}
        1
        2
        3
        4
        5
        6
        7
        <!-- goods.wxml -->
        <view>
        <view wx:for="{{dataList}}" wx:for-index="idx" wx:for-item="itemName">
        <!-- 商品{{index+1}}:{{item}} -->
        商品{{idx+1}}:{{itemName}}
        </view>
        </view>
      • 示例:循环字典
        1
        2
        3
        4
        5
        6
        7
        8
        9
        // goods.js
        Page({
        data: {
        userInfo: {
        name: '张三',
        age: 18
        }
        },
        )}
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        <!-- 循环字典 -->
        <!-- 单独获取 -->
        <view>
        {{userInfo.name}}
        {{userInfo.age}}
        </view>

        <!-- 循环获取 -->
        <view>
        <view wx:for="{{userInfo}}">{{index}} - {{item}}</view>
        </view>
    • block wx:for
      • 简介
        类似 block wx:if,也可以将 wx:for 用在 <block/> 标签上,以渲染一个包含多节点的结构块
      • 示例
        1
        2
        3
        4
        <block wx:for="{{[1, 2, 3]}}">
        <view> {{index}}: </view>
        <view> {{item}} </view>
        </block>
    • wx:key
      • 简介
        • 如果列表中项目的位置会动态改变或者有新的项目添加到列表中,并且希望列表中的项目保持自己的特征和状态(如 input 中的输入内容,switch 的选中状态),需要使用 wx:key 来指定列表中项目的唯一的标识符。
        • wx:key 的值以两种形式提供
          1. 字符串,代表在 for 循环的 array 中 item 的某个 property,该 property 的值需要是列表中唯一的字符串或数字,且不能动态改变。
          2. 保留关键字 *this 代表在 for 循环中的 item 本身,这种表示需要 item 本身是一个唯一的字符串或者数字。
        • 当数据改变触发渲染层重新渲染的时候,会校正带有 key 的组件,框架会确保他们被重新排序,而不是重新创建,以确保使组件保持自身的状态,并且提高列表渲染时的效率。
        • 如不提供 wx:key,会报一个 warning, 如果明确知道该列表是静态,或者不必关注其顺序,可以选择忽略。
      • 示例
        1
        2
        3
        4
        5
        6
        <switch wx:for="{{objectArray}}" wx:key="unique" style="display: block;"> {{item.id}} </switch>
        <button bindtap="switch"> Switch </button>
        <button bindtap="addToFront"> Add to the front </button>

        <switch wx:for="{{numberArray}}" wx:key="*this" style="display: block;"> {{item}} </switch>
        <button bindtap="addNumberToFront"> Add to the front </button>
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        38
        39
        Page({
        data: {
        objectArray: [
        {id: 5, unique: 'unique_5'},
        {id: 4, unique: 'unique_4'},
        {id: 3, unique: 'unique_3'},
        {id: 2, unique: 'unique_2'},
        {id: 1, unique: 'unique_1'},
        {id: 0, unique: 'unique_0'},
        ],
        numberArray: [1, 2, 3, 4]
        },
        switch: function(e) {
        const length = this.data.objectArray.length
        for (let i = 0; i < length; ++i) {
        const x = Math.floor(Math.random() * length)
        const y = Math.floor(Math.random() * length)
        const temp = this.data.objectArray[x]
        this.data.objectArray[x] = this.data.objectArray[y]
        this.data.objectArray[y] = temp
        }
        this.setData({
        objectArray: this.data.objectArray
        })
        },
        addToFront: function(e) {
        const length = this.data.objectArray.length
        this.data.objectArray = [{id: length, unique: 'unique_' + length}].concat(this.data.objectArray)
        this.setData({
        objectArray: this.data.objectArray
        })
        },
        addNumberToFront: function(e){
        this.data.numberArray = [ this.data.numberArray.length + 1 ].concat(this.data.numberArray)
        this.setData({
        numberArray: this.data.numberArray
        })
        }
        })
      • 注意事项
        • wx:for 的值为字符串时,会将字符串解析成字符串数组
        • 花括号和引号之间如果有空格,将最终被解析成为字符串
  • 条件渲染

    • wx:if
      • 简介
        在框架中,使用 wx:if="" 来判断是否需要渲染该代码块
      • 示例
        1
        <view wx:if="{{condition}}"> True </view>
        也可以用 wx:elif 和 wx:else 来添加一个 else 块
        1
        2
        3
        <view wx:if="{{length > 5}}"> 1 </view>
        <view wx:elif="{{length > 2}}"> 2 </view>
        <view wx:else> 3 </view>
    • block wx:if
      • 简介
        因为 wx:if 是一个控制属性,需要将它添加到一个标签上。如果要一次性判断多个组件标签,可以使用一个 <block/> 标签将多个组件包装起来,并在上边使用 wx:if 控制属性。
      • 示例
        1
        2
        3
        4
        <block wx:if="{{true}}">
        <view> view1 </view>
        <view> view2 </view>
        </block>
      • 注意
        <block/> 并不是一个组件,它仅仅是一个包装元素,不会在页面中做任何渲染,只接受控制属性。
  • 模板

    • 简介

      WXML 提供模板(template),可以在模板中定义代码片段,然后在不同的地方调用。

    • 定义模板

      使用 name 属性,作为模板的名字。然后在 <template/> 内定义代码片段,如:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      <!--
      index: int
      msg: string
      time: string
      -->
      <template name="msgItem">
      <view>
      <text> {{index}}: {{msg}} </text>
      <text> Time: {{time}} </text>
      </view>
      </template>
    • 使用模板

      使用 is 属性,声明需要的使用的模板,然后将模板所需要的 data 传入,如:

      1
      <template is="msgItem" data="{{...item}}"/>
      1
      2
      3
      4
      5
      6
      7
      8
      9
      Page({
      data: {
      item: {
      index: 0,
      msg: 'this is a template',
      time: '2016-09-15'
      }
      }
      })

      is 属性可以使用 Mustache 语法,来动态决定具体需要渲染哪个模板:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      <template name="odd">
      <view> odd </view>
      </template>
      <template name="even">
      <view> even </view>
      </template>

      <block wx:for="{{[1, 2, 3, 4, 5]}}">
      <template is="{{item % 2 == 0 ? 'even' : 'odd'}}"/>
      </block>
    • 模板的作用域

      模板拥有自己的作用域,只能使用 data 传入的数据以及模板定义文件中定义的 <wxs /> 模块。

  • 引用

    • 简介

      WXML 提供两种文件引用方式 importinclude

    • import

      import 可以在该文件中使用目标文件定义的 template,如:
      在 item.wxml 中定义了一个叫 itemtemplate

      1
      2
      3
      4
      <!-- item.wxml -->
      <template name="item">
      <text>{{text}}</text>
      </template>

      在 index.wxml 中引用了 item.wxml,就可以使用 item 模板:

      1
      2
      <import src="item.wxml"/>
      <template is="item" data="{{text: 'forbar'}}"/>
    • import 的作用域
      • import 有作用域的概念,即只会 import 目标文件中定义的 template,而不会 import 目标文件 import 的 template。
      • 如:C import B,B import A,在 C 中可以使用 B 定义的 template,在 B 中可以使用 A 定义的 template,但是 C 不能使用 A 定义的 template
        1
        2
        3
        4
        <!-- A.wxml -->
        <template name="A">
        <text> A template </text>
        </template>
        1
        2
        3
        4
        5
        <!-- B.wxml -->
        <import src="a.wxml"/>
        <template name="B">
        <text> B template </text>
        </template>
        1
        2
        3
        4
        <!-- C.wxml -->
        <import src="b.wxml"/>
        <template is="A"/> <!-- Error! Can not use tempalte when not import A. -->
        <template is="B"/>
    • include

      include 可以将目标文件除了 <template/> <wxs/> 外的整个代码引入,相当于是拷贝到 include 位置,如:

      1
      2
      3
      4
      <!-- index.wxml -->
      <include src="header.wxml"/>
      <view> body </view>
      <include src="footer.wxml"/>
      1
      2
      <!-- header.wxml -->
      <view> header </view>
      1
      2
      <!-- footer.wxml -->
      <view> footer </view>

WXS 语法参考

  • 介绍

    • WXS(WeiXin Script)是小程序的一套脚本语言,结合 WXML,可以构建出页面的结构。
    • WXS 与 JavaScript 是不同的语言,有自己的语法,并不和 JavaScript 一致。
  • 模块

    • WXS 模块

      WXS 代码可以编写在 wxml 文件中的 <wxs> 标签内,或以 .wxs 为后缀名的文件内。

    • 模块
      • 每一个 .wxs 文件和 <wxs> 标签都是一个单独的模块。
      • 每个模块都有自己独立的作用域。即在一个模块里面定义的变量与函数,默认为私有的,对其他模块不可见。
      • 一个模块要想对外暴露其内部的私有变量与函数,只能通过 module.exports 实现。
    • .wxs 文件

      微信开发者工具里面,右键可以直接创建 .wxs 文件,在其中直接编写 WXS 脚本。

  • 变量

    • 概念
      • WXS 中的变量均为值的引用。
      • 没有声明的变量直接赋值使用,会被定义为全局变量。
      • 如果只声明变量而不赋值,则默认值为 undefined
      • var 表现与 javascript 一致,会有变量提升。
      • 示例
        1
        2
        3
        var foo = 1;
        var bar = "hello world";
        var i; // i === undefined

        上面代码,分别声明了 foobari 三个变量。然后,foo 赋值为数值 1bar 赋值为字符串 "hello world"

    • 变量名

      变量命名必须符合下面两个规则:

      • 首字符必须是:字母(a-zA-Z),下划线(_)
      • 剩余字符可以是:字母(a-zA-Z),下划线(_), 数字(0-9)
    • 保留标识符

      以下标识符不能作为变量名:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      delete
      void
      typeof

      null
      undefined
      NaN
      Infinity
      var

      if
      else

      true
      false

      require

      this
      function
      arguments
      return

      for
      while
      do
      break
      continue
      switch
      case
      default
  • 注释

    WXS 主要有 3 种注释的方法。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    <!-- wxml -->
    <wxs module="sample">
    // 方法一:单行注释

    /*
    方法二:多行注释
    */

    /*
    方法三:结尾注释。即从 /* 开始往后的所有 WXS 代码均被注释

    var a = 1;
    var b = 2;
    var c = "fake";

    </wxs>

    上述例子中,所有 WXS 代码均被注释掉了。
    方法三 和 方法二 的唯一区别是,没有 */ 结束符。

  • 运算符

    • 基本运算符
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      var a = 10, b = 20;

      // 加法运算
      console.log(30 === a + b);
      // 减法运算
      console.log(-10 === a - b);
      // 乘法运算
      console.log(200 === a * b);
      // 除法运算
      console.log(0.5 === a / b);
      // 取余运算
      console.log(10 === a % b);

      加法运算(+)也可以用作字符串的拼接。

      1
      2
      3
      4
      var a = '.w' , b = 'xs';

      // 字符串拼接
      console.log('.wxs' === a + b);
    • 一元运算符
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      // 自增运算
      console.log(10 === a++);
      console.log(12 === ++a);
      // 自减运算
      console.log(12 === a--);
      console.log(10 === --a);
      // 正值运算
      console.log(10 === +a);
      // 负值运算
      console.log(0-10 === -a);
      // 否运算
      console.log(-11 === ~a);
      // 取反运算
      console.log(false === !a);
      // delete 运算
      console.log(true === delete a.fake);
      // void 运算
      console.log(undefined === void a);
      // typeof 运算
      console.log("number" === typeof a);
    • 位运算符
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      var a = 10, b = 20;

      // 左移运算
      console.log(80 === (a << 3));
      // 带符号右移运算
      console.log(2 === (a >> 2));
      // 无符号右移运算
      console.log(2 === (a >>> 2));
      // 与运算
      console.log(2 === (a & 3));
      // 异或运算
      console.log(9 === (a ^ 3));
      // 或运算
      console.log(11 === (a | 3));
    • 比较运算符
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      var a = 10, b = 20;

      // 小于
      console.log(true === (a < b));
      // 大于
      console.log(false === (a > b));
      // 小于等于
      console.log(true === (a <= b));
      // 大于等于
      console.log(false === (a >= b));
    • 等值运算符
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      var a = 10, b = 20;

      // 等号
      console.log(false === (a == b));
      // 非等号
      console.log(true === (a != b));
      // 全等号
      console.log(false === (a === b));
      // 非全等号
      console.log(true === (a !== b));
    • 赋值运算符
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      var a = 10;

      a = 10; a *= 10;
      console.log(100 === a);
      a = 10; a /= 5;
      console.log(2 === a);
      a = 10; a %= 7;
      console.log(3 === a);
      a = 10; a += 5;
      console.log(15 === a);
      a = 10; a -= 11;
      console.log(-1 === a);
      a = 10; a <<= 10;
      console.log(10240 === a);
      a = 10; a >>= 2;
      console.log(2 === a);
      a = 10; a >>>= 2;
      console.log(2 === a);
      a = 10; a &= 3;
      console.log(2 === a);
      a = 10; a ^= 3;
      console.log(9 === a);
      a = 10; a |= 3;
      console.log(11 === a);
    • 二元逻辑运算符
      1
      2
      3
      4
      5
      6
      var a = 10, b = 20;

      // 逻辑与
      console.log(20 === (a && b));
      // 逻辑或
      console.log(10 === (a || b));
    • 其他运算符
      1
      2
      3
      4
      5
      6
      var a = 10, b = 20;

      //条件运算符
      console.log(20 === (a >= 10 ? a + 10 : b + 10));
      //逗号运算符
      console.log(20 === (a, b));
  • 语句

    • if 语句

      在 WXS 中,可以使用以下格式的 if 语句 :

      • if (expression) statement : 当 expression 为 truthy 时,执行 statement
      • if (expression) statement1 else statement2 : 当 expression 为 truthy 时,执行 statement1。 否则,执行 statement2
      • if ... else if ... else statementN 通过该句型,可以在 statement1 ~ statementN 之间选其中一个执行。

      示例

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      // if ...

      if (表达式) 语句;

      if (表达式)
      语句;

      if (表达式) {
      代码块;
      }


      // if ... else

      if (表达式) 语句;
      else 语句;

      if (表达式)
      语句;
      else
      语句;

      if (表达式) {
      代码块;
      } else {
      代码块;
      }

      // if ... else if ... else ...

      if (表达式) {
      代码块;
      } else if (表达式) {
      代码块;
      } else if (表达式) {
      代码块;
      } else {
      代码块;
      }
    • switch 语句
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      switch (表达式) {
      case 变量:
      语句;
      case 数字:
      语句;
      break;
      case 字符串:
      语句;
      default:
      语句;
      }
      • default 分支可以省略不写。
      • case 关键词后面只能使用:变量数字字符串
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        var exp = 10;

        switch ( exp ) {
        case "10":
        console.log("string 10");
        break;
        case 10:
        console.log("number 10");
        break;
        case exp:
        console.log("var exp");
        break;
        default:
        console.log("default");
        }

        // 输出:number 10
    • for 语句
      1
      2
      3
      4
      5
      6
      for (语句; 语句; 语句)
      语句;

      for (语句; 语句; 语句) {
      代码块;
      }
      • 支持使用 breakcontinue 关键词。
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        for (var i = 0; i < 3; ++i) {
        console.log(i);
        if( i >= 1) break;
        }

        /*
        输出:
        0
        1
        */
    • while 语句
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      while (表达式)
      语句;

      while (表达式){
      代码块;
      }

      do {
      代码块;
      } while (表达式)
      • 表达式为 true 时,循环执行语句代码块
      • 支持使用 breakcontinue 关键词。
  • 数据类型

    • number : 数值
    • string :字符串
    • boolean:布尔值
    • object:对象
    • function:函数
    • array : 数组
    • date:日期
    • regexp:正则
  • 基础类库

    • console

      console.log 方法用于在 console 窗口输出信息。它可以接受多个参数,将它们的结果连接起来输出。

    • Math
      • 属性
        • E
        • LN10
        • LN2
        • LOG2E
        • LOG10E
        • PI
        • SQRT1_2
        • SQRT2

          以上属性的具体使用请参考 ES5 标准

      • 方法
        • atan
        • atan2
        • ceil
        • cos
        • exp
        • floor
        • log
        • max
        • min
        • pow
        • random
        • round
        • sin
        • sqrt
        • tan

          以上方法的具体使用请参考 ES5 标准。

    • JSON
      • 方法
        • stringify(object): 将 object 对象转换为 JSON 字符串,并返回该字符串。
        • parse(string): 将 JSON 字符串转化成对象,并返回该对象。
      • 示例
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        console.log(undefined === JSON.stringify());
        console.log(undefined === JSON.stringify(undefined));
        console.log("null"===JSON.stringify(null));

        console.log("111"===JSON.stringify(111));
        console.log('"111"'===JSON.stringify("111"));
        console.log("true"===JSON.stringify(true));
        console.log(undefined===JSON.stringify(function(){}));


        console.log(undefined===JSON.parse(JSON.stringify()));
        console.log(undefined===JSON.parse(JSON.stringify(undefined)));
        console.log(null===JSON.parse(JSON.stringify(null)));

        console.log(111===JSON.parse(JSON.stringify(111)));
        console.log("111"===JSON.parse(JSON.stringify("111")));
        console.log(true===JSON.parse(JSON.stringify(true)));

        console.log(undefined===JSON.parse(JSON.stringify(function(){})));
    • Number
      • 属性
        • MAX_VALUE
        • MIN_VALUE
        • NEGATIVE_INFINITY
        • POSITIVE_INFINITY

          以上属性的具体使用请参考 ES5 标准

    • Date
      • 属性
        • MAX_VALUE
        • MIN_VALUE
        • NEGATIVE_INFINITY
        • POSITIVE_INFINITY

          以上属性的具体使用请参考 ES5 标准

    • Global
      • 属性
        • NaN
        • Infinity
        • undefined

          以上属性的具体使用请参考 ES5 标准。

      • 方法
        • parseInt
        • parseFloat
        • isNaN
        • isFinite
        • decodeURI
        • decodeURIComponent
        • encodeURI
        • encodeURIComponent

          以上方法的具体使用请参考 ES5 标准。