小程序常用操作

setData操作优化

避免列表数据全局刷新、局部更新单条数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
this.setData({
'ceng.show': false
})

this.setData({
['people[' + index + '].age']: 25
})

// 也可以写成这样
this.setData({
[`people[${index}].age`]: 25
})

// 动态设置变量,filed为动态设置的变量
this.setData({
[filed]: 25
})

下拉加载更多避免直接使用concat或者push等方法

1
2
3
4
5
6
7
8
9
10
// 核心思想是使用二维数组的方式去存储列表,不过这样渲染时就需要渲染两层了
wx.request({
url: 'test.php',
success: res => {
let Length = this.data.arr.length;
that.setData({
[`arr${Length}`]: res.data // res.data 每一页请求过来的数据
})
}
})

主包体积优化

剔除不必要的打包文件

packOptions配置项文档

1
2
3
4
5
6
7
8
9
10
// 写在project.config.json文件里面

"packOptions": {
"ignore": [
{
"type": "file",
"value": "package-lock.json"
}
]
},

组件内使用全局样式

方法1

1
2
3
4
5
Component({
options: {
addGlobalClass: true
}
})

如果只想使用全局的某个class

具体描述可以查看文档

1
2
3
4
5
6
7
8
9
app.js 文件

.text-blue {
color: blue;
}

组件内

<view class="~text-blue"></view>

实现1px边框

1
2
3
4
5
6
7
8
9
10
11
12
13
.border-b:after {
position: absolute;
content: '';
width: 100%;
left: 0;
bottom: 0;
height: 1px;
background-color: #e3e5e9;
-webkit-transform: scale(1, 0.5);
transform: scale(1, 0.5);
-webkit-transform-origin: center bottom;
transform-origin: center bottom;
}

小程序登录逻辑

  1. 调用wx.getUserProfile获取用户头像、昵称等信息
  2. 调用wx.login获取登录凭证(code)
  3. 请求我们的后端,我们后端把 appid , appsecret 和 code 一起发送到微信服务器换取 openid
  4. 我们在自己的数据库中,查找 openid ,如果没有查到记录,说明该用户没有注册执行注册逻辑,如果有记录,则用自行维护的登录态判断token是否失效

参考资料:
如何打造高性能小程序门户
小程序如何避免setData的列表数据过大
小程序登录流程
登录流程2


小程序常用操作
https://xypecho.github.io/2020/05/11/小程序常用操作/
作者
很青的青蛙
发布于
2020年5月11日
许可协议