小程序中有两种引用方式一种是直接引用include,通过它相当于把<templete/>
标注的以外的代码全部copy过来当前位置,而import则是相反,它是只引用模板
- import方式
这是index.wxml中的代码
<!--src需要写入相对路径-->
<import src="../list/list.wxml"/>
<template is="listTemp"></template>
这是list.wxml中的代码
<!--不会被引用-->
<view >listView</view>
<!--会被引用-->
<template name="listTemp">
<view >我是模板</view>
</template>
<!--不会被引用-->
<template is="listTemp">
</template>
import引用作用域是有限制的,引用页面只能使用被引用页面的模板,不能使用被引用页面中引用其它页面模板的模板
这是index.wxml中的代码
<!--src需要写入相对路径引入list.wxml-->
<import src="../list/list.wxml"/>
<template is="listTemp"></template>
这是list.wxml中的代码
<!--src需要写入相对路径引入logs.wxml-->
<import src="../logs/logs.wxml"/>
<template is="logsTemp"></template>
<!--不会被引用-->
<view >listView</view>
<!--会被引用-->
<template name="listTemp">
<view >我是模板</view>
</template>
<!--不会被引用-->
<template is="listTemp">
</template>
这是logs.wxml中的代码
<!--不会被引用-->
<view >logsView</view>
<!--会被引用-->
<template name="logsTemp">
<view >我是logs模板</view>
</template>
<!--不会被引用-->
<template is="logsTemp">
</template>
可以看到index页面只是引用了list中的模板并没有引用logs的模板
- include方式
index页面
<!--src需要写入相对路径-->
<include src="../list/list.wxml"/>
list页面
<!--会被引用-->
<view >listView </view>
<!--不会被引用-->
<template name="listTemp">
<view >我是list模板:{{name}}</view>
</template>
<!--会被引用-->
<template is="listTemp" data="{{name}}">
</template>
(注意这里用到了name这个属性,我在这里测试了一下,在index.js的data中设置了name:“我是index数据源”,在list.js中也配置了name:”我是list数据源”,结果在引用的时候被引用页面的数据源总是取index.js中的数据,由此可见当用include时本路径下的数据时不引用的,组后我又测试了下点击事件等也都是不行的,可见无论是import方式还是include方式它就是一个引用,被引用的页面所有的交互只和当前引用页的逻辑js进行交互 )
最后总结就是import可以用来引用模板,在开发中可以避免相同模板的重复编写,而include适合引入组件文件