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
-->