欢迎光临
我们一直在努力

九八云百度小程序教程:引用

  • 引用
    • import
    • include

    引用

    SWAN 可以通过importinclude来引用模板文件。

    import

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

    代码示例

    在开发者工具中打开

    在开发者工具中打开

    在 WEB IDE 中打开

    • 首先,在person-card.swan中定义了一个叫person-cardtemplate
    
     
    1. <!-- person-card.swan-->
    2. <template name="person-card">
    3. <view>
    4. <text>位置: {{pos}}</text>
    5. <text>姓名: {{name}}</text>
    6. </view>
    7. </template>
    • 然后,在index.swan里引用文件person-card.swan,并使用它的模板:
    
     
    1. <!-- index.swan-->
    2. <import src="./person-card.swan" />
    3. <template is="person-card" data="{{person}}" />
    
     
    1. // index.js
    2. Page({
    3. data: {
    4. person: {
    5. pos: 'Baidu',
    6. name: 'SWAN'
    7. }
    8. }
    9. });

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

    代码示例

    在开发者工具中打开

    在开发者工具中打开

    在 WEB IDE 中打开

    
     
    1. <!-- templateA.swan-->
    2. <template name="A">
    3. <text> A template </text>
    4. </template>
    
     
    1. <!-- templateB.swan-->
    2. <import src="../templateA/templateA.swan"/>
    3. <template name="B">
    4. <text> B template </text>
    5. </template>
    6. <template is="A"/>
    
     
    1. <!-- templateC.swan-->
    2. <import src="../templateB/templateB.swan"/>
    3. <template is="A"/>
    4. <template is="B"/>

    include

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

    代码示例

    在开发者工具中打开

    在开发者工具中打开

    在 WEB IDE 中打开

    
     
    1. <!-- index.swan-->
    2. <include src="header.swan" />
    3. <view class="index">body</view>
    
     
    1. <!-- header.swan-->
    2. <view class="header">header</view>

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

    代码示例

    在开发者工具中打开

    在开发者工具中打开

    在 WEB IDE 中打开

    
     
    1. <!-- index.swan -->
    2. <include src="header.swan"/>
    3. <view> body </view>
    4. <include src="footer.swan"/>
    
     
    1. <!-- header.swan -->
    2. <view> header </view>
    
     
    1. <!-- footer.swan -->
    2. <view> footer </view>

    赞(0) 打赏
    未经允许不得转载:九八云安全 » 九八云百度小程序教程:引用

    评论 抢沙发