小程序代码复用 - template

时间:2022-07-25
本文章向大家介绍小程序代码复用 - template,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

为了提高代码的复用率,小程序提供了多种代码复用的模式,其中最简单的就是模板template。本文介绍一下如何定义模板及使用。

template定义

<template name="easy">
  <text class='red' data-name="{{name}}" bindtap="click">I'm Easy,{{greeting}}</text>  
</template>

<template name="Davi">
  <text>I'm Davi,nice to meet you</text>
</template>

使用data-name可以在事件中传递参数name给处理函数click

template使用

<import src="../../template/template.wxml" />

<view class="container">
  <!-- 引用template模板,用is="easy"的方式,选择模板 -->
  <template is="easy"  data="{{...person}}" />
  <template is="Davi" />
</view>

数据及事件处理

//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    person: {
      greeting: "你好",
      name: "tim"
    }
  },
  //事件处理函数
  click: function(e) {
    console.log(e);
    console.log(e.currentTarget.dataset.name);
  }
})

输出自定义参数e.currentTarget.dataset.name

注意事项

  • template并没有定义事件回调函数,需要在使用方定义(如果要有自定义的函数,可以使用小程序组件component)

参考