這篇文章主要為大家展示了“微信小程序如何實現模版渲染”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“微信小程序如何實現模版渲染”這篇文章吧。
微信小程序的界面程序支持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
}
}以上是“微信小程序如何實現模版渲染”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。