基于Vue2搭建的uniapp开发过程遇到的坑
站长
· 阅读数 18
1.关于uniapp 在onLaunch等生命周期中navigateTo/redirectTo跳转不生效问题(或只在真机上不生效)
tabBar页面为pages.json中"tabBar"中配置的页面,如果是则应该使用 uni.switchTab 跳转。
2.本地背景图在小程序页面不显示如何解决?
- 小程序不支持背景图使用本地图片
- 背景图支持base64格式,支持网络地址
- 可将背景图上传到服务器,使用网络地址
- 使用image标签代替背景图进行设置
<image class="imgbgc" heightFix src="/static/images/general/logo/logobgc.png"></image>
----------------------------------------------------------------------------------------
.imgbgc{
width: 100%;
height: 100%;
position:fixed;
// background-size:100% 100%;
z-index: -1;
}
3. 本地图片在开发工具可见,在真机编译的时候不可见如何解决?
- 保证图片路径没有中文字符
- 上传服务器用网络地址
- 使用本地动态加载
<image class="imgbot" :src="icon1" mode=""></image>
-----------------------------------------------------------------
data() {
return {
icon1: require('../../static/images/general/details/图层 503@2x.png'),
}
}
4. 登录模式的设计(前端)
- 登录页面onLoad周期里面请求数据通过uni.login获取微信登录获取code
- 通过code向后端发送请求获取openId(前端不可以自己通过官方文档去获取openId与session_key)
- 点击登录携带openId与账号密码请求后端登录接口即可
1.获取微信登录获取code
onLoad() {
this.wxLogin();
},
2. /**
* 微信小程序登陆获取oppenid
* 1. uni.login 获取微信小程序临时code
* 2. 利用 code 登陆我们的业务代码
* @returns userInfo: object
*/
wxLogin() {
return new Promise((resolve, reject) => {
// 微信登录获取code
uni.login({
provider: 'weixin',
onlyAuthorize: true, // 微信登录仅请求授权认证
success: async event => {
const { code } = event;
console.log('code', code);
console.log('uni.login获取临时code>>>', code);
await getOpenId(code) //2.通过code向后端发送请求获取openId
.then(res => {
console.log('后端返回oppenid>>>', res);
if (res.code === 200) {
this.openId = res.data.openid;
wx.setStorageSync('oppenId', this.openId);
} else {
uni.showToast({
title: res.message,
icon: 'none',
duration: 2000
});
}
})
.catch(err => {
uni.showToast({
title: err,
icon: 'none',
duration: 2000
});
});
},
fail: function(err) {
// 登录授权失败
console.log('登录授权失败', err);
resolve(false);
// err.code是错误码
}
});
});
}
3.携带参数请求后端数据接口
5. token过期时间内免登录
在App.vue文件中onLaunch周期函数下进行判断设置
onLaunch: function(options) {
console.log('App Launch', options);
// //检测是否已经登录
uni.getStorage({
key: 'token',
success: res => {
console.log(res);
if (res) {
uni.switchTab({
url: '/pages/tabbar/home/index'
});
console.log('res0000');
} else {
uni.navigateTo({
url: '/pages/index/index'
});
console.log('ree');
uni.getStorageSync('token', '');
}
},
fail: () => {
uni.navigateTo({
url: '/pages/index/index'
});
uni.getStorageSync('token', '');
}
});
},
6. 打包优化
- 图片等资源如果比较多可以放在服务器上,通过请求获取,不多存在本地,通过压缩图片减少图片体积达到要求即可
- 前端不要自己请求密钥跟openid就不会存在敏感信息
- 启用组件按需注入(在源码视图中找到 "mp-weixin",在其最后添加下面代码)
"lazyCodeLoading": "requiredComponents"
4.代码尽量放在分包实现 5.个别插件需要在源码视图中先注册,比如地图插件
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序定位"
}
},
7. 上线审核(打包优化全部完善)
填写可以登录自己小程序的测试号跟密码
代码里面不要出现密钥等敏感字符
正常审核一个小程序时间可能就几个小时