codecamp

百度智能小程序 引用

SWAN 可以通过 import 和 include 来引用模板文件。

import

通过 import 和 template 配合使用,可以将代码分离以及复用。

代码示例 

在开发者工具中打开
  • 首先,在person-card.swan中定义了一个叫person-card的template:
<!-- person-card.swan-->
<template name="person-card">
    <view>
        <text>位置: {{pos}}</text>
        <text>姓名: {{name}}</text>
    </view>
</template>
  • 然后,在index.swan里引用文件person-card.swan,并使用它的模板:
<!-- index.swan-->
<import src="./person-card.swan" />
<template is="person-card" data="{{person}}" />
// index.js
Page({
    data: {
        person: {
            pos: 'Baidu',
            name: 'SWAN'
        }
    }
});

import 具有递归的特性。 例如:C 引用 B,B 引用 A,在 C 中可以使用 B 定义的 template,在 B 中可以使用 A 定义的 template ,C 也可以使用 A 定义的 template

代码示例 

在开发者工具中打开
<!-- templateA.swan-->
<template name="A">
  <text> A template </text>
</template>
<!-- templateB.swan-->
<import src="../templateA/templateA.swan"/>

<template name="B">
  <text> B template </text>
</template>

<template is="A"/>
<!-- templateC.swan-->
<import src="../templateB/templateB.swan"/>

<template is="A"/>

<template is="B"/>

include

通过 include 可以将目标模板整个(除了 template)引入到当前的位置,相当于 inline。

代码示例 

在开发者工具中打开
<!-- index.swan-->
<include src="header.swan" />
<view class="index">body</view>
<!-- header.swan-->
<view class="header">header</view>


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

代码示例 

在开发者工具中打开
<!-- index.swan -->
<include src="header.swan"/>
<view> body </view>
<include src="footer.swan"/>
<!-- header.swan -->
<view> header </view>
<!-- footer.swan -->
<view> footer </view>


百度智能小程序 文件作用域
百度智能小程序 CSS
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

百度智能小程序开发文档

百度智能小程序 组件

百度智能小程序 地图

百度智能小程序 画布

百度智能小程序 API

百度智能小程序 界面

百度智能小程序 关注小程序引导组件

百度智能小程序 自定义组件

百度智能小程序 媒体

百度智能小程序 设备

百度智能小程序 拨打电话

百度智能小程序 内存警报

百度智能小程序 手机联系人

百度智能小程序 用户截屏事件

百度智能小程序 第三方平台

百度智能小程序 开放接口

百度智能小程序 百度收银支付

百度智能小程序 分包预下载

百度智能小程序 数据分析

百度智能小程序 服务端

百度智能小程序 云开发

百度智能小程序 初始化

百度智能小程序 云函数

百度智能小程序 服务端初始化

百度智能小程序 服务器获取上下文

百度智能小程序 服务端云函数

百度智能小程序 开发教程

百度智能小程序 功能开发

百度智能小程序 基本原理

百度智能小程序 小程序自动化

百度智能小程序 视频教程

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }