小程序中引用import和include区别

小程序中有两种引用方式一种是直接引用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方式
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模板
list引入logs模板
logs页面
可以看到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>

include方式
(注意这里用到了name这个属性,我在这里测试了一下,在index.js的data中设置了name:“我是index数据源”,在list.js中也配置了name:”我是list数据源”,结果在引用的时候被引用页面的数据源总是取index.js中的数据,由此可见当用include时本路径下的数据时不引用的,组后我又测试了下点击事件等也都是不行的,可见无论是import方式还是include方式它就是一个引用,被引用的页面所有的交互只和当前引用页的逻辑js进行交互
最后总结就是import可以用来引用模板,在开发中可以避免相同模板的重复编写,而include适合引入组件文件

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值