全部產品
Search
文件中心

Mobile Platform as a Service:引用

更新時間:Jul 13, 2024

AXML 提供兩種檔案引用方式 importinclude

import

import 可以載入已經定義好的 template。

例如,在 item.axml 中定義了一個名為 item 的 template。

<!-- item.axml -->
<template name="item">
  <text>{{text}}</text>
</template>

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

<import src="./item.axml"/>
<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。

<!-- a.axml -->
<template name="A">
  <text> A template </text>
</template>
<!-- b.axml -->
<import src="./a.axml"/>
<template name="B">
  <text> B template </text>
</template>
<!-- c.axml -->
<import src="./b.axml"/>
<template is="A"/>  <!-- 注意:不能使用 import A -->
<template is="B"/>

template 的子節點只能是一個,例如:

正確樣本:

<template name="x">
  <view />
</template>

錯誤樣本:

<template name="x">
  <view />
  <view />
</template>

include

include 可以將目標檔案除 <template/> 外整個代碼引入,相當於是拷貝到 include 位置。

程式碼範例:

<!-- index.axml -->
<include src="./header.axml"/>
<view> body </view>
<include src="./footer.axml"/>
<!-- header.axml -->
<view> header </view>
<!-- footer.axml -->
<view> footer </view>

引入路徑

模板引入路徑支援相對路徑、絕對路徑,也支援從 node_modules 目錄載入第三方模組。

<import src="./a.axml"/> <!-- 相對路徑 -->
<import src="/a.axml"/> <!-- 專案絕對路徑 -->
<import src="third-party/x.axml"/> <!-- 第三方 npm 包路徑 -->