小程序import与include

模板可以用单独的wxml来保存

使用的时候, 用import导入模板

创建模板数据的来源:

Page({
  data: {
    mo: 'Hello World!!',
    userid : '1234',
    text:'测试',
    list: [{
      index: 0,
      msg: "this is a template",
      time: "2016-09-15"
    },
    {
      index: 1000,
      msg: "this is a new template",
      time: "2026-09-15"
    }]
  },

创建模板文件(可以放在其它专用文件夹):

<!--模板独立成单独的文件-->

<template name="item">

  <view>template text: {{msg}}</view>
 
  <view>日期 : {{time}}</view>

</template>

使用import导入模板并使用:

<!--模板引用-->
<import src='../common/template.wxml'/>   

<view class='container'>

  <view wx:for='{{list}}'>
    <!--模板使用-->
    <template is='item' data="{{...item}}"/>
  </view>

</view>

is就是模板的名称, data是模板要使用的数据

...item是ES6简写的方式, 如果不用此方式, 则在模板定义中就是{{item.xxx}}, 而不是{{xxx}}

include用于拆分页面, 它不传递参数(template则可以传递参数)

由于很多页面的头部和底部是一样的

所以可以定义头部和底部, 再将它们包进不同的页面

header.wxml, footer.wxml

<import src='../common/template.wxml'/>
<view class='container'>

  <include src='../common/header.wxml'/>

  <view>
    <template is='item' data="{{xxx}}"/>
  </view>

  <include src='../common/footer.wxml'/>

</view> 

使用include标签完成页面包含, 使用import标签完成模板导入

include包含除template标签以外的代码, template只引入template标签的代码, 它们引入的内容正好相反

猜你喜欢

转载自blog.csdn.net/lljxk2008/article/details/81112860