前言
1.模闆的引入方式
WXML 提供兩種檔案引用方式import和include
- import:導入模闆并沒有真正的使用
- include:直接引入頁面元素,已經使用了
2.模闆群組件的比較
template(模闆):是可以在wxml中引用的代碼,就是在wxml中引用公用的wxml類型的代碼,它的作用類似于元件,是以這裡簡單的說明下template與Component (元件)的差別。
template(模闆)與Component (元件)的差別:
1.template(模闆):主要用于顯示,簡單的說主要是用于嵌入wxml的代碼,模闆中是可以擁有對應的樣式以及邏輯,但是他并沒有屬于的對應的js檔案,它的邏輯依賴于引用的頁面。
2.Component(元件):作為一個單獨的功能子產品,不僅可以包含頁面展示還可以包含該子產品的事件邏輯處理。像一個頁面一樣,Component元件可以包含wxml wxss js json 檔案。
總的來說,template(模闆)和Component (元件)非常相似,Component (元件)相比于template(模闆)更完整,接近于一個獨立的子產品,有自己的邏輯方法,是以在使用場景上會有一定的差別,template(模闆)更多的适用于僅僅是展示用的,而Component (元件)可用于業務上或者涉及的邏輯相對複雜的場景上進行使用。
一、import
import可以在該檔案中使用目标檔案定義的template,如:
在 item.wxml 中定義了一個叫item的template:
<template name="item">
<view>template text: {{msg}}</view>
<view>日期 : {{time}}</view>
</template>
在 index.wxml 中引用了 item.wxml,就可以使用item模闆:
<import src='../common/template.wxml'/>
<view class='container'>
<view wx:for='{{list}}'>
<!--模闆使用-->
<template is='item' data="{{...item}}"/>
</view>
</view>
二、import 的作用域
import 有作用域的概念,即隻會 import 目标檔案中定義的 template,而不會 import 目标檔案 import 的 template。
如:C import B,B import A,在C中可以使用B定義的template,在B中可以使用A定義的template,但是C不能使用A定義的template。
<!-- A.wxml -->
<template name="A">
<text> A template </text>
</template>
<!-- B.wxml -->
<import src="a.wxml"/>
<template name="B">
<text> B template </text>
</template>
<!-- C.wxml -->
<import src="b.wxml"/>
<template is="A"/> <!-- Error! Can not use tempalte when not import A. -->
<template is="B"/>
三、include
include 可以将目标檔案除了 <template/> <wxs/> 外的整個代碼引入,相當于是拷貝到 include 位置,如:
<!-- index.wxml -->
<include src="header.wxml"/>
<view> body </view>
<include src="footer.wxml"/>
<!-- header.wxml -->
<view> header </view>
<!-- footer.wxml -->
<view> footer </view>
四、案例
1.定義模闆
<template name="toast">
.......
</template>
2.使用模闆
<import src="tools/toast/toast.wxml"/>
<template is="toast" />
<import src="tools/toast/toast.wxml"/>
<template is="toast" />
<import src="tools/popup/popup.wxml"/>
<template is="popup" />
<import src="tools/xxx/xxx.wxml"/>
<template is="xxx" />
<import src="tools/toast/toast.wxml"/>
<import src="tools/popup/popup.wxml"/>
<template is="wetoast"/>
<template is="popup"/>
<include src="template.wxml" />