微信小程序开发笔记(三)——模板

为什么要用模板呢?

当多个页面需要有一样的组件时,使用模板会比较方便。

Table of Contents

一、定义模板

使用模板

二、使用模板

三、列表渲染+模板+页面传值

1. 列表渲染

 2. template.wxml里的模板、页面传值

3. js中的事件定义


一、定义模板

使用 name 属性,作为模板的名字。然后在<template/>内定义代码片段,如:

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

使用模板

二、使用模板

如果模板的定义不在当前的wxml文件里,使用之前记得先import!

使用 is 属性,声明需要的使用的模板,然后将模板所需要的 data 传入,如:

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

三、列表渲染+模板+页面传值

1. 列表渲染

首先记得import!

<import src="/pages/templates/template.wxml"/>
    <view hidden="{{isMonitor}}" class="infoBox2" wx:for="{{taskList}}" wx:for-index="idx" wx:for-item="task" hover-class="click-active">
      <template is="taskList" data="{{task:task, idx:idx, myId: myId, project:projectList[idx]}}" />
    </view>

    <view hidden="{{!isMonitor}}" class="infoBox2" wx:for="{{taskList}}" wx:for-index="idx" wx:for-item="task" hover-class="click-active">
      <template is="taskList" data="{{task:task, idx:idx, myId: myId, project:projectList[idx]}}" wx:if="{{task.monitorId==myId}}" />
    </view>

 2. template.wxml里的模板、页面传值

<template name="taskList">
  <view  class="{{myId==task.monitor.id? 'monitor' : ''}}" bindtap="toTaskInfo" data-task="{{task}}" data-project="{{project}}">
    <view class="block1">
      <view class="title"> 
        <view wx:if="{{myId !==task.monitorId}}" class="img"> <image src="/images/task.png" /> </view>
        <view wx:if="{{myId ==task.monitorId}}" class="img"> <image src="/images/monitor3.png" /> </view>
        <text> {{task.name}} </text>
      </view>
      <view class="status"> {{task.state}} </view>
    </view>

    <view class="block2">
      <view class="infoTitle"> 所属项目: </view>
      <view class="infoContent"> {{project.name}} </view>
    </view>

    <view class="block2">
      <view class="infoTitle"> 岗位描述: </view>
      <view class="infoContent"> {{task.description}} </view>
    </view>

    <view class="block2">
      <view class="infoTitle"> 起止日期: </view>
      <view class="infoContent"> {{"自"+ task.startDate+"至" +  task.endDate }} </view>
    </view>
  </view>
</template>

3. js中的事件定义

  /*跳转到岗位详情页*/
  toTaskInfo: function(e){
    console.log("e.currentTarget.dataset.task = ", e.currentTarget.dataset.task)
    var task = encodeURIComponent(JSON.stringify(e.currentTarget.dataset.task))
    var project = encodeURIComponent(JSON.stringify(e.currentTarget.dataset.project))
    wx.navigateTo({
      url: '../task/taskInfo/taskInfo?task=' + task + '&project=' + project,
    })
  },

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值