在小程序中,如果一套样式以及结构多处用到了,类似于Vue中的组件复用,那么小程序中也有一套模板语法去处理这类问题。
第一种模板语法
1、在项目的主目录新建一个templates目录
新建完templates目录后,在该目录内创建文件夹,以及生成wxml,wxss复用的代码样式
示例:

目录结构.png
common.wxml代码:
<template name="common">
<view class="common-header">
<view class="header-name">{{headerName}}</view>
<view class="header-user"><view>用户名:</view><view>{{helpTel}}</view></view>
</view>
</template>
common.wxss代码:
.common-header {
height: 30px;
width: 100%;
line-height: 30px;
display: flex;
background: cornsilk;
justify-content: space-around;
}
.header-name {
width: 50%;
height: 100%;
color: blueviolet;
}
.header-user {
width: 50%;
height: 100%;
display: flex;
text-align: right;
padding-right: 10px;
}
.header-user > view {
width: 50%;
}
.header-user view:nth-child(2){
color: #999;
text-align: center;
}
2、开始在其他页面导入
templates模板页面写完后,就开始在用到的页面中逐个导入
2.1、首页home导入
home.wxml导入部分的代码:
<import src="../../templates/common/common.wxml"></import>
<template is="common" data="{{headerName:'首页',helpTel:'小陈同学'}}"></template>
home.wxss导入部分的代码:
/* pages/home/home.wxss */
@import "../../templates/common/common.wxss";
其他使用到了的页面按照同样的方法去导入,数据使用微信小程序的data传入,里面的值对应template的插值区域的内容
大致效果:

模板共有的运行结果.png
第二种模板语法
1、外部页面使用include引入进来
新建的time.wxml:
<view>
当地时间:{{time}}
</view>
home.js代码:
// pages/home/home.js
var util = require('../../utils/util.js');
Page({
/**
* 页面的初始数据
*/
data: {
time:''
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var date = util.formatTime(new Date()); //获取当前时间
// 刷新页面
this.setData({
time:date
})
}
})
home.wxml代码:
引入time.wxml
<include src="./time.wxml"></include>

include模板.png