微信小程序中使用template来复用代码

1,063 阅读2分钟

笔者的小程序项目中某页面由多个布局类似的卡片组成,如下图所示:

由于这个些卡片的布局很相似、功能相同(点击后跳转到相应页面),所以不管是视图层还是逻辑层的代码我们都应该做到复用而不是写多遍(DRY ,Dont Repeat Yourself )。本文将和大家分享如何使用template来做代码复用的。

template的引入

template就是模板中定义的代码片段,然后可以在不同的地方调用。

我们定义template时,使用 name 属性作为模板的名字,然后在模板中定义代码片段,如下面代码所示:

<template name="homeItem">
  <view 
    bindtap="toSomePage" 
    data-number="{{number}}"  
    data-title="{{title}}" 
    class="home-item-container" 
    style="background: {{bgColor}}"
    >
  </view>
</template>

我们使用template时,首先需要使用import来导入,然后使用 is 属性来说明要使用哪一个template。类似vue中的props,我们可以使用data 传入模板所需要的数据。

<import src="../../components/home/homeItem"></import>
<template wx:for="{{homeItemList}}" wx:key="index" data="{{...item}}" is="homeItem" />

此处我们传递参数使用了解构,如果要显示地传多个值可以像下面代码这样做:

<view hidden="{{showType === 'done'}}">
  <template  data="{{todayAppointmentList,showType}}" is="appointment" />
</view>
<view hidden="{{showType === 'ready'}}">
  <template  data="{{tomorrowAppointmentList,showType}}" is="appointment" />
</view>

关于template的详细介绍请参见文末的参考资料【1】。

样式文件的引入

上面我们说了template的定义、导入以及使用,那么template对应的样式该如何引入呢?如下图所示,笔者将template和样式文件以及对应的逻辑层代码都放到同一目录下了:

为了导入template的样式我们可以使用@import语句,此语句是用来导入外联样式表,@import后跟需要导入的外联样式表的相对路径,用;表示语句结束,如下代码所示:

/**index.wxss**/
@import "../../components/home/homeItem.wxss";

js/ts文件的引入

以上两部分介绍了视图层代码如何复用,那么逻辑层代码该如何复用呢?例如,在上文中所展示的template的代码中,我们为view绑定了tap事件:bindtap="toSomePage",其中的事件处理函数toSomePage定义在homeItem.ts文件中,我们该如何引入呢?参见如下代码:

// homeItem.ts文件
export const homeItem = {
  toSomePage: (e: any) => {
    // 做一些事情
  }
}
// 页面对应的index.ts文件
import { homeItem } from '../../components/home/homeItem'
Page({
  ...homeItem,
  data: {
    windowHeight: 721,
    company_name: '',
  },
  async loginMqtt() {},
  getCode() {}
})

如上代码所示,首先在homeItem.ts文件中定义并导出了一个homeItem对象,对象中定义了toSomePage方法。然后在index.ts文件中导入homeItem对象,并将其定义的方法解构出来。

总结

本文和大家分享了在开发小程序时如何使用template来进行代码的复用,分别介绍了template如何定义和引入,样式文件如何引入,以及逻辑层的js(ts)代码如何引入。

本文正在参加「金石计划」,欢迎一起参与!

参考资料

【1】WXML 语法参考 /模板

【2】样式导入

【3】小程序框架 /逻辑层 /模块化

【4】微信小程序模板