微信小程序block和template区别与使用

一、block

<block/> 并不是一个组件,它仅仅是一个包装元素,不会在页面中做任何渲染,只接受控制属性。

1、判断

<block wx:if="{{true}}">
  <view> foo </view>
</block>
<block wx:else>
  <view> bar </view>
<block>

2、遍历

<block wx:for="{{[1, 2, 3]}}">
  <view> {{index}}: </view>
  <view> {{item}} </view>
</block>

二、template

<template/>用来在模板中定义代码片段,然后在不同的地方调用。
作用域:模板拥有自己的作用域,只能使用 data 传入的数据以及模板定义文件中定义的 <wxs/> 模块。

定义模板

<template name="msgItem">
  <view>
    <text> {{index}}: {{msg}} </text>
    <text> Time: {{time}} </text>
  </view>
</template>

使用

<template is="msgItem" data="{{...item}}"/>
Page({
  data: {
    item: {
      index: 0,
      msg: 'this is a template',
      time: '2016-09-15'
    }
  }
})

动态渲染

<template name="odd">
  <view> odd </view>
</template>
<template name="even">
  <view> even </view>
</template>

<block wx:for="{{[1, 2, 3, 4, 5]}}">
  <template is="{{item % 2 == 0 ? 'even' : 'odd'}}"/>
</block>
PS:写作不易,如要转裁,请标明转载出处。
%{ comment.page.total }条评论

猜你想看

微信小程序:前端开发宝典

最近文章
工具操作
  • 内容截图
  • 全屏
登录
注册
回顶部