一、組件與數據綁定
https://mp.weixin.qq.com/debug/wxadoc/dev/component/text.html
1、text組件與button組件
<text>text組件文本</text>
<button type="normal">normal button</button>
<button type="primary"> primary button </button>
這裏 button 標籤內 type 屬性用於設置按鈕風格
2、數據綁定
數據名用 {{}} 可對其內容在 .js 文件中進行綁定
<text>{{bindText_1}}</text>
Page({
data: {
bindText_1:"這是.js中綁定的數據文本"
},
})
二、button的點擊響應
下例通過 bindtap 屬性對 button 點擊事件進行響應
單擊按鈕後其顯示文字改變
<button type="primary" bindtap="btnclick"> {{btnText}} </button>
Page({
data:{
btnText:"default btn text"
},
btnclick: function () {
console.log("btnclick: function");
this.setData({btnText:"set new btn text"});
}
})
三、條件渲染
下例點擊按鈕後改變條件值從而改變文本
<button bindtap="btnclick">button</button>
<text wx:if="{{condition}}">滿足條件</text>
<text wx:else>不滿足條件</text>
Page({
data:{
condition:true
},
btnclick: function () {
var condition = this.data.condition;
//這裏condition需要在函數內先進行定義
//data中的condition不能直接拿來使用
console.log(condition);
this.setData({condition:!condition});
}
})
四、列表渲染
在組件上使用 wx:for 控制屬性綁定一個數組,即可使用數組中各項的數據重複渲染該組件。
<view wx:for="{{array}}">
{{index}} ------ {{item.message}}
</view>
默認數組的當前項的下標變量名默認爲 index,數組當前項的變量名默認爲 item
Page({
data: {
array: [{
message: '第0個文本',
}, {
message: '第一個文本'
}]
}
})
運行結果:
item.message即爲array數組中的message變量(array.message)
上述結果與一下運行結果相同
Page({
data: {
array: [
'第0個文本', '第一個文本'
]
}
})
使用 wx:for-item 可以指定數組當前元素的變量名,
使用 wx:for-index 可以指定數組當前下標的變量名:
<view wx:for="{{array}}" wx:for-index="idx" wx:for-item="itemName">
{{idx}}: {{itemName.message}}
</view>
五、頁面引用
1、include
include 可以將目標文件除了 <template/>
<wxs/>
外的整個代碼引入,相當於是拷貝到 include 位置,如:
<!-- pages/demo/demo.wxml -->
<include src="../template/header.wxml"/>
<view> body </view>
<!-- pages/template/header.wxml -->
<view> header </view>
2、template
下例 import 了 footer.wxml 使用其中名爲 footer2 的模板
<!-- pages/demo/demo.wxml -->
<!--此處對footer.wxml引入,還未分配模板-->
<import src="../template/footer.wxml"/>
<!--此處決定模板的使用,同時能對模板爲定義的數據進行定義-->
<template is="footer2" data="{{text: 'footer template'}}"/>
<!-- pages/template/footer.wxml -->
<template name="footer1">
<text>{{text}} 1</text>
</template>
<template name="footer2">
<text>{{text}} 2</text>
</template>
3、import 的作用域
import 有作用域的概念,即只會 import 目標文件中定義的 template,而不會 import 目標文件 import 的 template。
如:C import B,B import A,在C中可以使用B定義的template,在B中可以使用A定義的template,但是C不能使用A定義的template。