开发 .swan 文件

这部分是每个智能小程序页面的展现模板,类似于 Web 开发中的 HTML,SWAN 模板中使用的标签均为 SWAN 组件规定的标签。 代码示例

  1. <view s-for="item in items" class="single-item" bind:tap="oneItemClick" bind:touchstart="oneItemTouchStart" bind:touchmove="oneItemTouchmove" bind:touchcancel="oneItemTouchcancel" bind:touchend="oneItemTouchEnd"> <image src="{{item.imgsrc}}" class="single-img"></image> <view class="single-text-area"> <text class="single-title"> {{item.title}} </text> <view s-if="{{item.tags}}" class="tag-area"> <text s-for="tag in item.tags" class="{{tag.className}}"> {{tag.content}} </text> </view> </view></view><view class="view-more" bind:tap="loadMore"> <text>点击加载更多</text></view>

标签可以拥有属性,需要注意的是,swan中的属性是大小写敏感的,也就是说 class 和 Class 在swan中是不同的属性。 代码示例 在开发者工具中预览效果

  1. <text class="wrap">hello world</text><text Class="wrap">hello world</text>

一个文件夹可以有两个swan文件。 代码示例 在开发者工具中预览效果

基础数据绑定

代码示例

  1. <!-- xxx.swan -->
  2. <view>
  3. Hello My {{ name }}
  4. </view>
  1. // xxx.js
  2. Page({
  3. data: {
  4. name: 'SWAN'
  5. }
  6. });

循环

s-for指令,来渲染一个列表。 代码示例

  1. <view>
  2. <view s-for="p in persons">
  3. {{p.name}}
  4. </view>
  5. </view>
  1. Page({
  2. data: {
  3. persons: [
  4. {name: 'superman'},
  5. {name: 'spiderman'}
  6. ]
  7. }
  8. });

条件

s-if指令,来在视图层进行逻辑判断: 代码示例

  1. <view s-if="is4G">4G</view>
  2. <view s-elif="isWifi">Wifi</view>
  3. <view s-else>Other</view>
  1. Page({
  2. data: {
  3. is4G: true,
  4. isWifi: false
  5. }
  6. });

事件

事件处理

bind: + 事件名来进行事件绑定 代码示例

  1. <view class="view-more" bind:tap="loadMore">
  2. 点击加载更多
  3. </view>
  1. Page({
  2. loadMore: function () {
  3. console.log('加载更多被点击');
  4. }
  5. });

目前支持的事件类型有:

事件对象

当开发者绑定方法到事件,事件触发时,SWAN 会给触发的方法传递事件对象,事件对象因事件不同而不同,目前基础的事件对象结构为:

dataset

开发者可以在组件中自定义数据,并在事件发生时,由 SWAN 所在事件对象中,传递给绑定函数。 代码示例

  1. <view data-swan="1" bind:tap="viewtap">dataset-test</view>
  1. Page({
  2. viewtap: function (event) {
  3. console.log('value is:', event.currentTarget.dataset.swan);// 输出1
  4. }
  5. });

属性值也可以动态的去改变,有所不同的是,属性值必须被包裹在双引号中, 且引号可加可不加 代码示例

  1. <view data-swan={{test}} bind:tap="viewtap">dataset-test</view>
  2. // 同<view data-swan="{{test}}" bind:tap="viewtap">dataset-test</view>
  1. Page({
  2. data: {
  3. test: 1
  4. },
  5. viewtap: function (event) {
  6. console.log('value is:', event.currentTarget.dataset.swan);// 输出1
  7. }
  8. });

需要注意的是变量名是大小写敏感的,也就是说 test 和 Test 是两个不同的变量。 代码示例

  1. <view data-swan="{{test}}" bind:tap="viewtap">dataset-test</view>
  1. Page({
  2. data: {
  3. test: 1,
  4. Test: 2
  5. },
  6. viewtap: function (event) {
  7. console.log('value is:', event.currentTarget.dataset.swan);// 输出1
  8. }
  9. });

touches

开发者在接收到触摸类事件后,在事件对象上,可以接收到当前停留在屏幕上的触摸点。 Touch 对象 代码示例

  1. <view bind:touchstart="viewtouchstart">viewtouchstart</view>
  1. Page({
  2. viewtouchstart: function (event) {
  3. console.log('value is:', event.touches);
  4. // 输出 clientX: 44,clientX: 47,pageX: 44, pageY: 47
  5. }
  6. });