一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第20天,点击查看活动详情。
前言
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 可以将目标文件除了