记录uniapp开发遇到的问题

299 阅读2分钟

1、图表使用u-charts,但是canvas因为是原生框架,所有会有层级问题,只能将生成好的图表转成图片

lineCharts[this.canvasId].addEventListener('renderComplete', () => {
        // #ifdef MP-WEIXIN
        uni.canvasToTempFilePath({
                x: 0,
                y: 0,
                width: this.cWidth,
                height: this.cHeight,
                canvasId: this.canvasId,
                success(res) {
                        console.log(res.tempFilePath, "dd");
                        _this.charImg = res.tempFilePath;
                },
                fail(err) {
                        console.log(err, "eee");
                }
        }, this);
        // #endif
})

2、小程序不支持background-image,可以转换成base64,或者用image和view去定位渲染。

3、顶部适配小程序时,需要注意状态栏的高度,和右上角小程序自带的按钮

const res = uni.getSystemInfoSync();
this.height = res.statusBarHeight;

4、上传文件

createFile(fileView, field) {
        // #ifndef H5 || MP-WEIXIN
        var _self = this;
        var input = document.createElement('input'); //创建元素
        input.type = 'file' //添加file类型
        input.accept = "application/pdf,application/msword";
        input.style = "height:100%;width:100%";
        input.id = field;
        input.onchange = (event) => {
                _self.uploadFile(input, event, field)
        }
        if (this.$refs[fileView] instanceof Array)
                this.$refs[fileView][0].$el.appendChild(input)
        else
                this.$refs[fileView].$el.appendChild(input)
        // #endif
},
uploadContentUrl() {
        const _this = this;
        // #ifndef H5 || MP-WEIXIN
        document.getElementById('contentUrl').click()
        // #endif
        // #ifdef H5
        uni.chooseFile({
                count: 1,
                extension: ['.docx', '.doc'],
                success: function(res) {
                        _this.uploadFile(res, null, 'contentUrl');
                }
        })
        //#endif
        // #ifdef MP-WEIXIN
        wx.chooseMessageFile({
                count: 1,
                extension: ['.docx', '.doc'],
                success: function(res) {						
                        _this.uploadFile(res, null, 'contentUrl');
                }
        })
        // #endif
},
/**
 * 上传文件
 * @param {Object} opts
 */
async uploadFile(el, e, field) {
    const _self = this;
    let options = {
            // fileType: ['doc', 'docx', 'pdf']
            fileType: ['doc', 'docx']
    };
    //文件
    let ret = null, uri = "";

    // #ifndef H5 || MP-WEIXIN
            ret = el.files[0];
            uri = e.srcElement.value;
    // #endif
    // #ifdef H5
            ret = el.tempFiles[0];
            uri = el.tempFilePaths[0];
    // #endif
    // #ifdef MP-WEIXIN
            ret = el.tempFiles[0];
            uri = ret.path;
    // #endif			

    const docType = ret.name.substr(ret.name.lastIndexOf(".") + 1);
    //判断文件类型
    const isJPG = options.fileType.find(d => d == docType) ? true : false;
    //判断文件大小
    const isLt2M = ret.size / 1024 / 1024 < 5;

    if (!ret)
            return;

    if (!isJPG) {
            uni.showToast({
                    icon: 'none',
                    title: `仅支持${options.fileType.toString()}文件,大小不能大于5M!`
            });
    } else if (!isLt2M) {
            uni.showToast({
                    icon: 'none',
                    title: "大小不能超过5MB!"
            });
    } else {

            //判断token是否过期
            const token = await checkToken();

            uni.uploadFile({
                    url: 'xx',
                    // files: [{
                    // 	file: ret,
                    // 	uri: uri
                    // }],
                    filePath: uri,
                    name: 'file',
                    header: {
                            'token': token, //读取cookie
                            'Tenant': tenantConfig()
                    },
                    success: (uploadFileRes) => {
                            const data = JSON.parse(uploadFileRes.data);
                            if (data.code == '200')
                                    _self[field] = data.path;
                            else
                                    console.log("");
                    },
                    fail: (err) => {
                            console.log(err);
                    }
            });
    }
}

5、uniapp打包时,会将vue页面中import的css内容打到文件中,导致每个引用了这个css样式的文件内都有相同css内容,所以css文件最好是只引用一次,可放到app.vue中引入,这样就不会超出小程序的打包限制

6、公众号:initWxConfig方法加载临时票据(放在onReady或者mounted周期内),weChatConfig是后端返回配置信息

initWxConfig() {
    weChatConfig({
            url: window.location.href
    }).then(res => {
            const e = JSON.parse(res.rows);
            this.$wx.config({
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                    appId: e.appId, // 必填,公众号的唯一标识
                    timestamp: e.timestamp, // 必填,生成签名的时间戳
                    nonceStr: e.nonceStr, // 必填,生成签名的随机串
                    signature: e.signature, // 必填,签名
                    jsApiList: ['checkJsApi', 'getLocation', 'openLocation', 'scanQRCode'] // 必填,需要使用的JS接口列表
            });
    })
},

checkWxJs(arr){
    this.$wx.checkJsApi({
            jsApiList: arr,
            success: function(res) {
                    let tempJsApi = res[0];
                    if (res.checkResult[tempJsApi] == false) {
                            uni.showToast({
                                    icon: 'none',
                                    title: '你的微信版本太低,不支持微信JS接口,请升级到最新的微信版本!'
                            });
                            return;
                    }
            },
            fail: function(res) {
                    console.info('checkJsApi fail=' + JSON.stringify(res))
            }
    });
}

scanner() {
    const _this = this;
    // #ifdef H5
    this.$wx.ready(() => {
        //校验js
        this.checkWxJs(['scanQRCode']);

        this.$wx.scanQRCode({
                needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
                scanType: ["qrCode"], // 可以指定扫二维码还是一维码,默认二者都有
                success: function(res) {
                        let result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果
                        if (result) {
                                try {
                                        let content = JSON.parse(result);
                                        
                                } catch (e) {

                                }
                        }
                }
        });
})
// #endif
// #ifndef H5
uni.scanCode({
        success: function(res) {
                console.log('条码内容:' + res.result);
                const content = res.result;
                
        }
});
// #endif
},

6、快捷登录,获取openid

//快捷登录
const url = window.location.href;
const codeIndex = url.indexOf('?code=');
if (codeIndex) {
        let code = url.substring(codeIndex + 6);
        code = code.substring(0, code.indexOf("#"))
        if (code) {
                //企业授权登录
                wxLogin({
                        code: code
                }).then(res => {

                })
        }
}

7、文件预览

   <view>
	<!-- #ifndef MP-WEIXIN -->
	<web-view :webview-styles="webviewStyles" :src="path" class="webView_div"></web-view>
	<!-- #endif -->
	<!-- #ifdef MP-WEIXIN -->
	<view class="back_btn">
		点击返回
	</view>
	<!-- #endif -->
</view>

<script>
export default {
data() {
	return {
		webviewStyles: {
			progress: {
				color: '#FF3333'
			}
		},
		path: ''
	};
},
onLoad(opt) {
	const lastend = opt.path.substring(opt.path.lastIndexOf('.') + 1);
	if (lastend == 'doc' || lastend == 'docx') {
		this.path = opt.path;
		
		// #ifdef MP-WEIXIN
		let path = this.path;
		wx.downloadFile({
			url: path,
			success: res => {
				let filePath = res.tempFilePath;
				console.log(filePath);
				wx.openDocument({
					filePath: filePath,
					fileType: lastend,
					success: () => {
						console.log('打开文档成功');
					}
				});
			}
		});
		// #endif
	} else {
		
	}
}
};
</script>

注:项目过大,小程序需要分包,分包大小不超过2M,总共不超过20M

8、日期格式需要改成/反斜杠的格式,在苹果手机中-会导致异常