微信小程序模版渲染详解

(编辑:jimmy 日期: 2024/9/28 浏览:2)

微信小程序的界面程序支持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 
  } 
 } 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

一句话新闻

微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。