微信小程序模版渲染详解

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

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

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容