【微信小程序】template模板使用详解

  WXML提供模板(template),可以在模板中定义代码片段,然后在不同的地方调用。

  模板的作用域:

  模板拥有自己的作用域,只能使用 data 传入的数据以及模板定义文件中定义的 <wxs /> 模块。

定义模板

复制代码
<template name='allgood-item'>
  <image src='{{icon}}' class='all_item_image'/>
  <view class='all_item_right'>
    <text class='all_item_title'>{{title}}</text>
    <view class='all_item_details'>
      <view>
        <text class='all_item_new'>{{newPrice}}</text>
        <text class='all_item_old'>{{oldPrice}}</text>
      </view>
      <text class='all_item_buy'>立即购买</text>
    </view>
  </view>
</template>
复制代码

使用模板

<import src='./allgood-item-template/allgood-item-template.wxml'/>

<block wx:for='{{modelArray}}'>
    <template is='allgood-item' data='{{...item}}' />
</block>

  微信小程序结合使用ES6+的解构和属性延展,我们给template传递一批属性更为方便了。

定义模板样式

.all_item_image {
   ...    
}
   ...
.all_item_new,.all_item_old,.all_item_buy{
   ...
}

引用模板样式

@import './allgood-item-template/allgood-item-template.wxss';

template进行绑定事件

<block wx:for='{{modelArray}}'>
  <view class='all_item_view' bindtap='toDetails'>
    <template is='allgood-item' data='{{...item}}' />
  </view>
</block>

 

posted @   Mr·Xu  阅读(1030)  评论(0编辑  收藏  举报
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 百万级群聊的设计实践
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
点击右上角即可分享
微信分享提示