小程序二--数据操作

1. 定义数据

在小程序中,我们的数据都是定义在.js文件中。具体位置,如下:

Page({
  data: {
    text: 'jack',
  },
  onLoad: function () {
  
  }
})

2. 关联到view

当我们在data:{......}中定义好数据后,主要是通过{{}}.wxml文件中进行引用。

   hello {{text}} !

上面的代码最终的结果: hello jack !

3. 数组的操作

  1. data中定义数组:
data: {
  array: [{
        id: 1,
        data: "hello"
      },
      {
        id: 2,
        data: "world"
      },
      {
        id: 3,
        data: "你好"
      },
      {
        id: 4,
        data: "世界"
      }
    ],
}
  1. wxml中调用:
   
     {{array[0].id+"---"+array[0].data}}
   

最终的结果:1---hello

4. 条件判断

.wxml文件中,我们可以直接通过wx:ifwx:else等判断条件,对UI渲染出不同的效果。

  
    我是红色
  
  
    我是蓝色
  

这段代码里,当used=true时显示我是红色,当used=false时显示我是蓝色。
并不是控件,仅仅是一个包装元素,不在页面中做渲染,仅仅接受控制属性。所以下面这种写法效果也是一致的。

    我是红色
    我是蓝色

个人推荐第二种写法,感觉代码看起来更简洁。

4. 列表

4.1 遍历列表

很多时候,我们的页面中,会有列表的展示。这种情况,我们可以使用wx:for来进行遍历:

  
    {{item.data}}
  

上面的代码,执行之后的结果如下:


Snip20181030_1.png
4.2 列表模板
  1. 创建一个template目录,专门用于存放模板文件
  2. 在template目录下,创建一个.wxml用于描述模板UI

这里的name用于标识当前模板

  1. 在template目录下,创建.wxss文件用于存放模板所用样式
.item_user {
  display: flex;
  flex-direction: column;
}

.title {
  font-size: 40rpx;
  color: black;
}

.user_info {
  width: 100%;
  display: flex;
  padding-left: 20rpx;
  flex-direction: column;
  background-color: #ff9e2e;
}

.text,
.text2 {
  height: 50rpx;
  font-size: 30rpx;
  line-height: 50rpx;
  border-bottom: 1rpx solid grey;
}

.text2 {
  border-bottom: 0;
}
  1. 在目标.wxml文件中,导入模板UI,并引用


.......
  
    
  
  1. 在目标.wxss文件中,导入模板样式文件
@import "../../template/user.wxss";
  1. 在目标.js文件中,创建数据
 userList: [{
      name: "李磊",
      gender: "男",
      age: 22
    }, {
      name: "韩梅梅",
      gender: "女",
      age: 20
    }, {
      name: "lily",
      gender: "女",
      age: 19
    }],

这样整个列表模板展示就完成了,最终效果如下:


Snip20181030_2.png

你可能感兴趣的:(小程序二--数据操作)