Getting Started with Small Programs

Data binding
The dynamic data in WXML comes from the data of the corresponding Page.

1. Simple binding
Data binding uses Mustache syntax (double braces) to wrap variables, which can be used for:
1.1 Content

<view> {{ message }} </view>
Page({
  data: {
    message: 'Hello MINA!'
  }
})

 1.2 Component properties (need to be within double quotes)

<view id="item-{{id}}"> </view>
Page({
  data: {
    id: 0
  }
})

 1.3 Control attributes (need to be within double quotes)

<view wx:if="{{condition}}"> </view>
Page({
  data: {
    condition: true
  }
})

 1.4 Keywords (need to be enclosed in double quotes)

true: true of type boolean, representing the true value.
false: false of type boolean, representing a false value.
<checkbox checked="{{false}}"> </checkbox>

Special attention: Do not write checked="false" directly, the result of the calculation is a string, which is converted into a boolean type to represent the true value.

2.
Simple operations can be performed within {{}}, and the following methods are supported:
2.1 Ternary operations

<view hidden="{{flag ? true : false}}"> Hidden </view>

2.2 Arithmetic operations

<view> {{a + b}} + {{c}} + d </view>
Page({
  data: {
    a: 1,
    b: 2,
    c: 3
  }
})
The content in the view is 3 + 3 + d.

 2.3 Logical judgment

<view wx:if="{{length > 5}}"> </view>
String operations
<view>{{"hello" + name}}</view>
Page({
  data:{
    name: 'MINA'
  }
})

 2.4 Datapath Operations

<view>{{object.key}} {{array[0]}}</view>
Page({
  data: {
    object: {
      key: 'Hello '
    },
    array: ['MINA']
  }
})

 3. Combination

You can also combine directly within Mustache to form new objects or arrays.

3.1 Arrays

<view wx:for="{{[zero, 1, 2, 3, 4]}}"> {{item}} </view>
Page({
  data: {
    zero: 0
  }
})
Finally combined into an array [0, 1, 2, 3, 4].

 3.2 Objects

<template is="objectCombine" data="{{for: a, bar: b}}"></template>
Page({
  data: {
    a: 1,
    b: 2
  }
})
The final combined object is {for: 1, bar: 2}

 You can also use the spread operator... to spread an object

<template is="objectCombine" data="{{...obj1, ...obj2, e: 5}}"></template>
Page({
  data: {
    obj1: {
      a: 1,
      b: 2
    },
    obj2: {
      c: 3,
      d: 4
    }
  }
})
The final combined object is {a: 1, b: 2, c: 3, d: 4, e: 5}.

 If the object's key and value are the same, it can also be expressed indirectly.

<template is="objectCombine" data="{{foo, bar}}"></template>
Page({
  data: {
    foo: 'my-foo',
    bar: 'my-bar'
  }
})
The resulting object is {foo: 'my-foo', bar: 'my-bar'}.

 Note: The above methods can be combined at will, but if there are variables with the same name, the latter will overwrite the former, such as:

<template is="objectCombine" data="{{...obj1, ...obj2, a, c: 6}}"></template>
Page({
  data: {
    obj1: {
      a: 1,
      b: 2
    },
    obj2: {
      b: 3,
      c: 4
    },
    a: 5
  }
})
The final combined object is {a: 5, b: 3, c: 6}.

 

Conditional rendering wx:if
In the framework, we use wx:if="{{condition}}" to determine whether the code block needs to be rendered:

<view class="red" wx:if="{{color=='red'}}"> red </view>
<view class="green" wx:elif="{{color=='green'}}"> green </view>
<view class="blue" wx:else> blue </view>

wx:if vs hidden
because the template in wx:if may also contain data binding, so when the condition value of wx:if is toggled, the framework has a partial rendering process, because it will ensure that the conditional block is destroyed when it is toggled or Re-render.
At the same time wx:if is also lazy, if the initial rendering condition is false, the framework does nothing, and only starts partial rendering when the condition becomes true for the first time.
In contrast, hidden is much simpler, the component will always be rendered, and it is just a simple control to show and hide.
In general, wx:if has higher switching cost and hidden has higher initial rendering cost. Therefore, hidden is better if you need to switch frequently, and wx:if is better if conditions are unlikely to change at runtime.

wx:for
Use the wx:for control property on a component to bind an array to repeatedly render the component with the data of each item in the array.
The subscript variable name of the current item of the default array defaults to index, and the variable name of the current item of the array defaults to item

<view wx:for="{{array}}">
  <view class="red">{{index}}. {{item.name}}</view>
</view>
//js
data: {
    array : [
      {name:"小明", age: 18},
      {name:"Li Lei", age: 19}
    ]
}

 Use wx:for-item to specify the variable name of the current element of the array, and use wx:for-index to specify the variable name of the current subscript of the array:

<view wx:for="{{array}}" wx:for-index="ix" wx:for-item="vals">
  <view class="red">{{ix}}. {{vals.name}}</view>
</view>

wx:for can also nest
a nine-nine multiplication table example:

<view wx:for="{{[1, 2, 3, 4, 5, 6, 7, 8, 9]}}" wx:for-item="i">
  <view wx:for="{{[1, 2, 3, 4, 5, 6, 7, 8, 9]}}" wx:for-item="j">
    <view wx:if="{{i <= j}}">
      {{i}} * {{j}} = {{i * j}}
    </view>
  </view>
</view>

block wx:for
is similar to block wx:if, but wx:for can also be used on the <block/> tag to render a multi-node structure block. E.g:

<block wx:for="{{[1, 2, 3]}}">
  <view> {{index}}: </view>
  <view> {{item}} </view>
</block>

wx:key
if the position of the item in the list changes dynamically or a new item is added to the list, and you want the item in the list to keep its own characteristics and state (such as the input content in <input/>, the content of <switch/> selected), you need to use wx:key to specify a unique identifier for the item in the list.
The value of wx:key provides strings in two forms
, representing a property of the item in the array of the for loop. The value of the property needs to be a unique string or number in the list, and cannot be changed dynamically.
The reserved keyword *this represents the item itself in the for loop. This representation requires the item itself to be a unique string or number. For example,
when the data change triggers the rendering layer to re-render, the component with the key will be corrected. The framework will ensure that they are reordered, not recreated, to ensure that components maintain their own state, and to improve the efficiency of list rendering.
If wx:key is not provided, a warning will be reported. If you know that the list is static, or you don't need to pay attention to its order, you can choose to ignore it.
Sample code:

<switch wx:for="{{objectArray}}" wx:key="unique" style="display: block;"> {{item.id}} </switch>
<button bindtap="addToFront"> Add to the front </button>
//js part
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]
  },
  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
    })
  }
})

 

Template
WXML provides a template (template), you can define code snippets in the template, and then call in different places.
Define the template
using the name attribute, as the name of the template. Then define code snippets inside <template/> like:

<!--
  index: int
  msg: string
  time: string
-->
<template name="msgItem">
  <view>
    <text> {{index}}: {{msg}} </text>
    <text> Time: {{time}} </text>
  </view>
</template>

Use the template
to use the is attribute, declare the required template, and then pass in the data required by the template, such as:

 

<template is="msgItem" data="{{...item}}"/>
Page({
  data: {
    item: {
      index: 0,
      msg: 'this is a template',
      time: '2016-09-15'
    }
  }
})

The is attribute can use Mustache syntax to dynamically determine which template needs to be rendered:

<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>

 template scope

Templates have their own scope and can only use the data passed in by data.

引用
WXML 提供两种文件引用方式import和include。
import
import可以在该文件中使用目标文件定义的template,如:
在 item.wxml 中定义了一个叫item的template:

<!-- item.wxml -->
<template name="item">
  <text>{{text}}</text>
</template>

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

<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。

<!-- A.wxml -->
<template name="A">
  <text> A template </text>
</template>
<!-- B.wxml -->
<import src="a.wxml"/>
<template name="B">
  <text> B template </text>
</template>
<!-- C.wxml -->
<import src="b.wxml"/>
<template is="A"/>  <!-- Error! Can not use tempalte when not import A. -->
<template is="B"/>

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

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

什么是事件
事件是视图层到逻辑层的通讯方式。
事件可以将用户的行为反馈到逻辑层进行处理。
事件可以绑定在组件上,当达到触发事件,就会执行逻辑层中对应的事件处理函数。
事件对象可以携带额外信息,如 id, dataset, touches。

 

事件的使用方式
在组件中绑定一个事件处理函数。
如bindtap,当用户点击该组件的时候会在该页面对应的Page中找到相应的事件处理函数。

<view id="tapTest" data-hi="WeChat" bindtap="tapName"> Click me! </view>
在相应的Page定义中写上相应的事件处理函数,参数是event。
Page({
  tapName: function(event) {
    console.log(event)
  }
})
可以看到log出来的信息大致如下:
{
"type":"tap",
"timeStamp":895,
"target": {
  "id": "tapTest",
  "dataset":  {
    "hi":"WeChat"
  }
},
"currentTarget":  {
  "id": "tapTest",
  "dataset": {
    "hi":"WeChat"
  }
},
"detail": {
  "x":53,
  "y":14
},
"touches":[{
  "identifier":0,
  "pageX":53,
  "pageY":14,
  "clientX":53,
  "clientY":14
}],
"changedTouches":[{
  "identifier":0,
  "pageX":53,
  "pageY":14,
  "clientX":53,
  "clientY":14
}]
}

事件详解
事件分类
事件分为冒泡事件和非冒泡事件
冒泡事件:当一个组件上的事件被触发后,该事件会向父节点传递。
非冒泡事件:当一个组件上的事件被触发后,该事件不会向父节点传递。
WXML的冒泡事件列表:

类型                      触发条件
touchstart            手指触摸动作开始
touchmove             手指触摸后移动
touchcancel           手指触摸动作被打断,如来电提醒,弹窗
touchend              手指触摸动作结束
tap                   手指触摸后马上离开
longtap               手指触摸后,超过350ms再离开

注:除上表之外的其他组件自定义事件如无特殊申明都是非冒泡事件,如<form/>的submit事件,<input/>的input事件,<scroll-view/>的scroll事件

 

事件绑定
事件绑定的写法同组件的属性,以 key、value 的形式。
key 以bind或catch开头,然后跟上事件的类型,如bindtap, catchtouchstart
value 是一个字符串,需要在对应的 Page 中定义同名的函数。不然当触发事件的时候会报错。
bind事件绑定不会阻止冒泡事件向上冒泡,catch事件绑定可以阻止冒泡事件向上冒泡。

 

如在下边这个例子中,点击 inner view 会先后触发handleTap3和handleTap2(因为tap事件会冒泡到 middle view,而 middle view 阻止了 tap 事件冒泡,不再向父节点传递),点击 middle view 会触发handleTap2,点击 outter view 会触发handleTap1。

<view id="outter" bindtap="handleTap1">
  outer view
  <view id="middle" catchtap="handleTap2">
    middle view
    <view id="inner" bindtap="handleTap3">
      inner view
    </view>
  </view>
</view>

事件对象
如无特殊说明,当组件触发事件时,逻辑层绑定该事件的处理函数会收到一个事件对象。
BaseEvent 基础事件对象属性列表:

属性             类型       说明
type             String     事件类型
timeStamp        Integer    事件生成时的时间戳
target           Object     触发事件的组件的一些属性值集合
currentTarget    Object     当前组件的一些属性值集合

CustomEvent 自定义事件对象属性列表(继承 BaseEvent):

属性    类型    说明
detail    Object    额外的信息

TouchEvent 触摸事件对象属性列表(继承 BaseEvent):

属性               类型      说明
touches            Array     触摸事件,当前停留在屏幕中的触摸点信息的数组
changedTouches     Array     触摸事件,当前变化的触摸点信息的数组
特殊事件:        <canvas/>  中的触摸事件不可冒泡,所以没有 currentTarget。

type
代表事件的类型。
timeStamp
页面打开到触发事件所经过的毫秒数。
target
触发事件的源组件。

属性    类型    说明
id    String    事件源组件的id
tagName    String    当前组件的类型
dataset    Object    事件源组件上由data-开头的自定义属性组成的集合

currentTarget
事件绑定的当前组件。

属性    类型    说明
id    String    当前组件的id
tagName    String    当前组件的类型
dataset    Object    当前组件上由data-开头的自定义属性组成的集合
说明:
 target 和 currentTarget 可以参考上例中,点击 inner view 时,handleTap3 收到的事件对象 
target 和 currentTarget 都是 inner,而 handleTap2 收到的事件对象 target 就是 
inner,currentTarget 就是 middle。

dataset
在组件中可以定义数据,这些数据将会通过事件传递给 SERVICE。 书写方式: 以data-开头,多个单词由连字符-链接,不能有大写(大写会自动转成小写)如data-element-type,最终在 event.target.dataset 中会将连字符转成驼峰elementType。
示例:

<view data-alpha-beta="1" data-alphaBeta="2" bindtap="bindViewTap"> DataSet Test </view>
Page({
  bindViewTap:function(event){
    event.target.dataset.alphaBeta === 1 // - 会转为驼峰写法
    event.target.dataset.alphabeta === 2 // 大写会转为小写
  }
})

touches
touches 是一个数组,每个元素为一个 Touch 对象(canvas 触摸事件中携带的 touches 是 CanvasTouch 数组)。 表示当前停留在屏幕上的触摸点。
Touch 对象

属性    类型    说明
identifier    Number    触摸点的标识符
pageX, pageY    Number    距离文档左上角的距离,文档的左上角为原点 ,横向为X轴,纵向为Y轴
clientX, clientY    Number    距离页面可显示区域(屏幕除去导航条)左上角距离,横向为X轴,纵向为Y轴

CanvasTouch 对象

属性    类型    说明    特殊说明
identifier    Number    触摸点的标识符    
x, y    Number    距离 Canvas 左上角的距离,Canvas 的左上角为原点 ,横向为X轴,纵向为Y轴
changedTouches
changedTouches 数据格式同 touches。 表示有变化的触摸点,如从无变有(touchstart),位置变化(touchmove),从有变无(touchend、touchcancel)。

detail
自定义事件所携带的数据,如表单组件的提交事件会携带用户的输入,媒体的错误事件会携带错误信息,详见组件定义中各个事件的定义。

 

 

Guess you like

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