小程式模版渲染詳解,小程式模版渲染詳解
小程式的介面程式支援html文法,多加了一部分標籤,如view、block、templete等。
模版渲染
index.wxml
<view> <p>{{helloWord}}</p></view>
其中{{}}裡麵包含的內容你可以理解為一個變數,怎麼讓程式解析出{{helloWord}}變數
在index.js 中註冊這個變數
var json = { data:{ "helloWord" : "hello world" }};page(json)
然後我們運行小程式,就可以發現顯示的就是hello world,即所有的變數都需要包含在註冊介面的data中
有的人可能會問,怎麼去動態添加這些變數呢?
var json = { data:{ "helloWorld":"" }, //監聽頁面載入 onLoad:function(){ var that = this; that.setData({ "helloWorld":"hello world" }) }};page(json)
甚至我們還可以
var json = { data:{}, //監聽頁面載入 onLoad:function(){ var that = this; that.setData({ "helloWorld":"hello world" }) }};page(json)
都能實現相同效果,每次調用setData()函數的是夠都會重新渲染一次頁面。
index1.wxml
<view> <view wx:for="{{users}}" wx:for-item="{{item}}"> <view wx:for="{{item}}" wx:for-index="{{key}}" wx:for-item="{{val}}"> <p>{{key}}=>{{val}}</p> </view> </view> <view id="nameDemo"> <p>name : {{users[0].name}}</p> </view> <view> <button bindtap="clickFunc">我是測試按鈕</button> </view></view>
index1.js
var json={ data:{}, //監聽頁面顯示 onShow:function(){ vat that = this; that.setData({ users:[ { "name":"name1", "age":100 }, { "name":"name2", "age":101 } ] }); }};page(json);
其中變數that的作用是對this的範圍的一個擴充。
wx:for 迴圈一個變數
wx:for-index 代表迴圈的鍵名
wx:for-item 代表迴圈的索引值
users 在頁面顯示的時候動態添加到了data範圍中。
現在我們再來看一個新的問題 如上id=”nameDemo” view中{{users[0].name}} 這個值我們怎麼去動態更改問題
有的可能說直接重建一個json直接渲染進去不就行了?
這種方案是可以的,但是要考慮到渲染的效能呀,如果每次調用都重新渲染一次,卡死你。
解決方案就是js的小技巧
只更改{{users[0].name}}的值
var json = { data:{}, //監聽頁面顯示 onShow:function(){ vat that = this; that.setData({ users:[ { "name":"name1", "age":100 }, { "name":"name2", "age":101 } ] }); }, clickFunc:function(event){ vat that = this; var dataJson = {}; dataJson["users[0].name"] = "我是誰"; that.setData(dataJson); }}
其中bindtap 給button對象添加了一個點擊事件,點擊事件對應的函數是clickFunc 參數event資料結構如下
{ "type": "tap", "timeStamp": 1252, "target": { "id": "tapTest", "offsetLeft": 0, "offsetTop": 0 }, "currentTarget": { "id": "tapTest", "offsetLeft": 0, "offsetTop": 0, "dataset": { "hi": "MINA" } }, "touches": [{ "pageX": 30, "pageY": 12, "clientX": 30, "clientY": 12, "screenX": 112, "screenY": 151 }], "detail": { "x": 30, "y": 12 } }
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。