微信小程序中include和import的区别

概念


import
import是用来导入模板。

include
includes用来导入除模板以外的内容。


区别

一、引用区别


看例子

一、创建一个文件夹test,里面包含一个test.wxml(只做模板测试,其他文件可省略);
二、test.wxml内容

<template name="test">
     template inner
</template>

template outer

三、在index页面中导入该test.wxml,(注意:同一个文件即可以被import也可被includes)
第一段代码:

//将test.wxml中的template中的内容到进来
<import src='./test/test.wxml' />
<template is="test" />

第二段代码:


//将test.wxml中template以外的内容导进来
<include src='tools/test/test.wxml' />

第一段和第二段可以同时存在,

当只有第一段代码时,index.wxml中的内容是

template inner

当只有第二段代码时,index.wxml中的内容是

template outer

当两段代码同时存在,index.wxml中的内容是

template inner template outer

一、引用区别


import有作用域的概念,即在一个文件中导入test模板,则只能在当前这个文件使用这个模板,在其他文件中是不能使用test模板的。

例子:
testA.wxml

<template name="testA">
     testA template 
</template>

testB.wxml

<import src='./testA.wxml' />
<template is="testA" />

<template name="testB">
     testB template 
</template>

index.wxml

<import src='../../tools/test/testb.wxml' />
<template is="testB" />
<template is="testA" />

报错

appservice:30 WXMLRT_$gwx:index.wxml:template:35:14: Template `testA` not found

可以把include理解成复制粘贴。


testA.wxml

<template name="testA">
    testA template
</template>
    testA template outer

testB.wxml

<include src='./testa.wxml'/>
<template name="testB">
    testB template
</template>
    testB template outer

index.wxml

<include src='../../tools/test/testb.wxml' />

渲染后的index.wxml

testA template outer testB template outer

结合使用


使用场景:
比如,你使用template自定义了一个toast框,形如这样:

<template name="toast">
    .......
</template>

在页面中使用,则需要这样:

<import src="tools/toast/toast.wxml"/>
<template is="toast" />

并且,每个页面都需要引用一遍。这时候,又自定义了一个popup框,每个需要popup的页面,又都需要引用一遍popup.wxml。不仅如此,当你的小程序越来越大,自定义的模板越来越多,每个页面都是下面这种样子:

<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" />
........

还有一个就是,当你改变某个自定义组件的路径,则每个页面都需要改变一次;这时候,我们可以利用include的属性

<import src="tools/toast/toast.wxml"/>
<import src="tools/popup/popup.wxml"/>
<template is="wetoast"/>
<template is="popup"/>
......

每个使用自定义组件的页面,只需要一句代码即可,

<include src="template.wxml" />

只需要固定template.wxml的位置,即便更改自定义组件的路径,在template中更改一次即可。是不是又偷到懒了~~~


猜你喜欢

转载自blog.csdn.net/zhy13087344578/article/details/79627507