支付宝小程序框架 AXML·引用

2020-09-18 10:28 更新

axml 提供两种文件引用方式 importinclude

import

import 可以加载已经定义好的 template

比如,在 item.axml 中定义了一个叫 itemtemplate

  1. <!-- item.axml -->
  2. <template name="item">
  3. <text>{{text}}</text>
  4. </template>

在 index.axml 中引用 item.axml,就可以使用 item 模板。

  1. <import src="./item.axml"/>
  2. <template is="item" data="{{text: 'forbar'}}"/>

import 有作用域的概念,只会 import 目标文件中定义的 template,而不会 import 目标文件 import 的 template。

比如,C import B,B import A,在 C 中可以使用 B 定义的 template,在 B 中可以使用 A 定义的 template,但是 C 不能使用 A 中定义的 template。

  1. <!-- a.axml -->
  2. <template name="A">
  3. <text> A template </text>
  4. </template>
  5. <!-- b.axml -->
  6. <import src="./a.axml"/>
  7. <template name="B">
  8. <text> B template </text>
  9. </template>
  10. <!-- c.axml -->
  11. <import src="./b.axml"/>
  12. <template is="A"/> <!-- 注意:不能使用 import A -->
  13. <template is="B"/>

注意 template 的子节点只能是一个,例如:

允许的示例:

  1. <template name="x">
  2. <view />
  3. </template>

不允许的示例:

  1. <template name="x">
  2. <view />
  3. <view />
  4. </template>

include

include 可以将目标文件除 <template/> 外整个代码引入,相当于是拷贝到 include 位置。

代码示例:

  1. <!-- index.axml -->
  2. <include src="./header.axml"/>
  3. <view> body </view>
  4. <include src="./footer.axml"/>
  5. <!-- header.axml -->
  6. <view> header </view>
  7. <!-- footer.axml -->
  8. <view> footer </view>

引入路径

模板引入路径支持相对路径、绝对路径,也支持从 node_modules 目录载入第三方模块。

  1. <import src="./a.axml"/> <!-- 相对路径 -->
  2. <import src="/a.axml"/> <!-- 项目绝对路径 -->
  3. <import src="third-party/x.axml"/> <!-- 第三方 npm 包路径 -->
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号