微信小程序开发笔记(一)

这篇博客介绍了在小程序中如何实现本地存储、数据更新、时间格式化和列表渲染。通过示例代码展示了wx.getStorageSync、wx.setStorageSync、Array.map方法的使用,并探讨了等于操作符(==)和全等操作符(===)的区别。此外,还演示了模板的使用,包括静态和动态模板加载。
摘要由CSDN通过智能技术生成

 

 1、展示本地存储能力

    const logs = wx.getStorageSync('logs') || []
    // 把当前时间戳插入到数组最前面
    logs.unshift(Date.now())
    // 将数组转换为字符串并输出到命令行
    console.log(logs.toString())
    wx.setStorageSync('logs', logs)

2、常用代码

// 获取应用实例
const app = getApp()

// 引用logs.js
const util = require('../../utils/util.js')

// 更新数据

Page({
  data: {
    logs: []
  },
  onLoad() {
    this.setData({
      logs:[]
      })
    })
  }
})

3、关于map

this.setData({
      logs: (wx.getStorageSync('logs') || []).map(log => {
        return util.formatTime(new Date(log))
      })
    })

4、通用方法formatTime封装和导出

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

module.exports = {
  formatTime
}


// 需要的地方引入logs.js
const util = require('../../utils/util.js')
// 使用formatTime
util.formatTime(new Date())

5、

==操作符会先将两边的值进行强制类型转换再比较是否相等,而===操作符不会进行类型转换。==操作符只要求比较两个值是否相等,而===操作符不仅要求值相等,而且要求类型相同。!=!==的区别也是类似的,!=号会做强制类型转换,而!==不会。

// true
55 == '55'
// false
55 === '55'

6、 列表渲染wx:for

  //js
  data: {
    week: [1,2,3,4,5,6,7], 
  }

  // wxml
  <block wx:for="{{week}}">
      <view>
          <text>{{index}}:星期{{item}}</text>
      </view>
  </block>


  在开发中,我们经常会遇到展示列表数据的需求,在小程序中需要使用标签 wx:for / wx:for-index / wx:for-item 来实现相关功能,运行效果如下所示。
wx:for="{{mainListViewData}}"        : 定义循环,数组名称为 mainListViewData 
wx:for-index="mainListViewDataIndex" : 定义索引值的名称 mainListViewDataIndex
wx:for-item="mainListViewDataItem"   : 定义索引值对应项名称 mainListViewDataItem

7、模板使用示例

<!--
item: {
  index: 0,
  msg: 'this is a template',
  time: '2016-06-18'
}
-->


<template name="msgItem">
  <view>
    <text> {{index}}: {{msg}} </text>
    <text> Time: {{time}} </text>
  </view>
</template>


<template is="msgItem" data="{{...item}}"/>

<!-- 输出
0: this is a template Time: 2016-06-18
-->

 动态加载模板示例

<template name="odd">
  <view> odd </view>
</template>


<template name="even">
  <view> even </view>
</template>


<block wx:for="{{[1, 2, 3, 4, 5]}}">
  <template is="{{item % 2 == 0 ? 'even' : 'odd'}}"/>
</block>



<!-- 输出
odd
even
odd
even
odd
-->

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值