数据绑定
数据绑定和许多模板引擎一样,数据包裹在双大括号里面。
双向绑定的数据需包裹在中。
例如:
组件 scroll-view 中,scroll-top 和 scroll-left 的使用方法分别为:
scroll-top="{= scrollTop =}"
scroll-left="{= scrollLeft =}"
- SWAN
- JS
// data-demo.js
Page({
data: {
name: 'SWAN App'
}
});
代码示例
- SWAN
- JS
<!-- attr-demo.swan -->
<view class="c-{{className}}">属性绑定</view>
注:属性不需要被双大括号包裹。
- SWAN
- JS
<!-- condition-demo.swan -->
<view s-if="flag">如果为flag为true,你看得到我。</view>
// condition-demo.js
Page({
flag: true
}
});
SWAN 模板提供了丰富的表达式类型支持,让使用者在编写视图模板时更方便。
- 数据访问(普通变量、属性访问)
- 一元否定
- 二元运算
- 二元关系
- 三元条件
- 括号
- 字符串
- 数值
- 布尔
通过下面例子列举支持的表达式类型。
- SWAN
对象字面量(对象字面量是三个大括号包裹)
代码示例
- SWAN
- JS
<template name="tag-card">
<view>
<text>标签: {{tag}}</text>
<text>昵称: {{nickname}}</text>
</view>
</template>
<template name="person-card">
<view>
<text>位置: {{pos}}</text>
</view>
</template>
<template name="team-card">
<view s-for="item, index in teams">
<text>球队: {{index}} - {{item}}</text>
</view>
</template>
<template name="age-card">
<view>
<text>年龄: {{age}}</text>
</view>
</template>
<template is="person-card" data="{{person}}" />
<!-- 对象字面量 -->
<template is="team-card" data="{{ {teams} }}" />
<template is="tag-card" data="{{ {tag, nickname: 'king'} }}" />
<template is="age-card" data="{{ {...person} }}" />
// template-demo.js
Page({
data: {
person: {name: 'Lebron James', pos: 'SF', age: 33},
teams: ['Cleveland Cavaliers', 'Miami Heat', 'Los Angeles Lakers'],
tag: 'basketball'
});