### [微信小程序的模版渲染](https://www.prosaas.cn/article/17682) **Published:** 2018-03-23T02:15:29 **Author:** 5201314 **Excerpt:** 这次给大家带来微信小程序的模版渲染,使用微信小程序模版渲染的注意事项有哪些,下面就是实战案例,一起来看一下。这… 这次给大家带来微信小程序的模版渲染,使用微信小程序模版渲染的注意事项有哪些,下面就是实战案例,一起来看一下。 这篇文章主要为大家详细介绍了微信小程序模版渲染的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 微信小程序的界面程序支持html语法,多加了一部分标签,如view、block、templete等。 模版渲染 index.wxml {{helloWord}} 其中{{}}里面包含的内容你可以理解为一个变量,怎么让程序解析出{{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 {{key}}=>{{val}} name : {{users\[0\].name}} 我是测试按钮 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 } } 相信看了本文案例你已经掌握了方法,更多精彩请关注知企PROSAAS其它相关文章! 推荐阅读: CSS3实现倾斜和旋转动画效果 inline-block元素默认间距清除 CSS3阴影box-shadow功能的使用详解 以上就是微信小程序的模版渲染的详细内容,更多请关注知企PROSAAS其它相关文章! **Categories:** 后端开发 ---
{{helloWord}}
{{key}}=>{{val}}
name : {{users\[0\].name}}