数据绑定

    数据绑定和许多模板引擎一样,数据包裹在双大括号里面。
    双向绑定的数据需包裹在中。

    例如
    组件 scroll-view 中,scroll-top 和 scroll-left 的使用方法分别为:

    • scroll-top="{= scrollTop =}"
    • scroll-left="{= scrollLeft =}"
    • SWAN
    • JS
    1. // data-demo.js
    2. Page({
    3. data: {
    4. name: 'SWAN App'
    5. }
    6. });

    代码示例

    • SWAN
    • JS
    1. <!-- attr-demo.swan -->
    2. <view class="c-{{className}}">属性绑定</view>

    :属性不需要被双大括号包裹。

    • SWAN
    • JS
    1. <!-- condition-demo.swan -->
    2. <view s-if="flag">如果为flag为true,你看得到我。</view>
    1. // condition-demo.js
    2. Page({
    3. flag: true
    4. }
    5. });

    SWAN 模板提供了丰富的表达式类型支持,让使用者在编写视图模板时更方便。

    • 数据访问(普通变量、属性访问)
    • 一元否定
    • 二元运算
    • 二元关系
    • 三元条件
    • 括号
    • 字符串
    • 数值
    • 布尔

    通过下面例子列举支持的表达式类型。

    • SWAN

    对象字面量(对象字面量是三个大括号包裹)

    代码示例

    • SWAN
    • JS
    1. <template name="tag-card">
    2. <view>
    3. <text>标签: {{tag}}</text>
    4. <text>昵称: {{nickname}}</text>
    5. </view>
    6. </template>
    7. <template name="person-card">
    8. <view>
    9. <text>位置: {{pos}}</text>
    10. </view>
    11. </template>
    12. <template name="team-card">
    13. <view s-for="item, index in teams">
    14. <text>球队: {{index}} - {{item}}</text>
    15. </view>
    16. </template>
    17. <template name="age-card">
    18. <view>
    19. <text>年龄: {{age}}</text>
    20. </view>
    21. </template>
    22. <template is="person-card" data="{{person}}" />
    23. <!-- 对象字面量 -->
    24. <template is="team-card" data="{{ {teams} }}" />
    25. <template is="tag-card" data="{{ {tag, nickname: 'king'} }}" />
    26. <template is="age-card" data="{{ {...person} }}" />
    1. // template-demo.js
    2. Page({
    3. data: {
    4. person: {name: 'Lebron James', pos: 'SF', age: 33},
    5. teams: ['Cleveland Cavaliers', 'Miami Heat', 'Los Angeles Lakers'],
    6. tag: 'basketball'
    7. });