项目最开始是在公众号上面,现在移植到小程序,做了两个星期,将常用的写法记录下来.
1. 获取全局变量..首先在app.js中定义你的变量,然后使用getApp().data.name 获取
App({
data: {
pgresid: "",
openid: "",
orgid: "",
userid: "",
username: "",
urlprefix: "http://xxx.xxx.com/",
surveyfloder: "picture/survey/",
videofloder: "video/survey",
mapkey: "JSCBZ-P3Q3G-2B4QA-INJ5O-6GC6J-UHBW7",
innerfloder: "内景照片",
outfloder: "外景照片",
scenefloder: "现场拍照",
enclosurefloder: "附件",
servsers: "https://xxx.xxx.com/mobile/",
//servsers: "http://localhost:8081/evaluate_web/mobile/",
html: '<div class="toolbar"><div class="tool-tip"><div class="loading"><div class="loader"><div class="item"></div><div class="item"></div><div class="item"></div><div class="item"></div><div class="item"></div></div></div><div class="title">正在努力加载...</div></div></div>',
userId: ""
},
})
例如我要获取接口域名地址 getApp().data.servsers,
2.用户登录后我们会将用户信息储存到缓存中,需要使用,下面是我自动登录的一段代码,如果缓存中获取用户信息有问题,或者未获取用户信息,就会直接跳登录页面,如果登录成功就进入index页面.
onLaunch: function() {
//调用API从本地缓存中获取数据
var logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs);
var that = this;
//本地缓存获取userId
try {
var userId = wx.getStorageSync('userId')
if (userId == undefined || userId == "") {
//console.log("重新登录");
//需要重新登录
wx.redirectTo({
url: 'pages/login/login'
});
return;
} else {
// 登录
wx.login({
success: res => {
if (res.code) {
//发起网络请求
wx.request({
url: getApp().data.servsers + "dataInterfaceLoginForMobile/checUser.shtml",
data: {
userId: userId
},
success: function(res) {
var msg = res.data.msg;
var user = res.data.user;
if (msg == "success") {
//将用户数据放入本地缓存
try {
wx.setStorageSync('userId', user.id);
wx.setStorageSync('userName', user.userName);
wx.setStorageSync('phoneNo', user.phoneNo);
wx.setStorageSync('openid', user.openid);
wx.setStorageSync('platType', user.plat_type);
wx.redirectTo({
//url: '../index/index'
});
} catch (e) {}
}
}
})
} else {
console.log('获取用户登录态失败!' + res.errMsg)
}
}
})
}
} catch (e) {
// Do something when catch error
}
})
3.js绑定值,在页面中展示.进入index页面后 在index页面初始化数据
Page({
data: {
business: [
{ ID: "1", icon: "fa-car", text: "车辆待评估", amount: carSurveyCount,searchType : "carSurvey",show : "N" },
{ ID: "2", icon: "fa-home", text: "房产待评估", amount: houseSurveyCount, searchType: "houseSurvey", show: "N" },
{ ID: "3", icon: "fa-briefcase", text: "待尽调业务", amount: jdCount, searchType: "jd", show: "N"},
{ ID: "4", icon: "fa-check-square", text: "待审核业务", amount: examineCount, searchType: "examine", show: "N" },
{ ID: "5", icon: "fa-legal", text: "待处理权证", amount: qzCount, searchType: "dqz", show: "N" },
{ ID: "6", icon: "fa-pencil-square", text: "待整改业务", amount: zgCount, searchType: "dzg", show: "N" }
],
//用户个人信息
userInfo: {
avatarUrl: "",//用户头像
nickName: "",//用户昵称
userName: "",
institutionName: ""//机构名
}
},
})
在index.wxml 获取用户userInfo信息,注意看获取信息的写法
<view class="userInfo">
<text class="text-css name">{{userInfo.userName}}</text>
<text class="text-css">{{userInfo.institutionName}}</text>
</view>
循环获取business 数组的信息
<view class="weui-cells__title">常用功能</view>
<view class="common">
<view class="item" wx:for="{{business}}" id="{{item.ID}}" data-searchtype="{{item.searchType}}" wx:key="item.ID" bindtap="redirectTo" wx:if="{{item.show=='Y'}}">
<view class="content" >
<view class="fa {{item.icon}}">
<text class="weui-badge text-number" wx:if="{{item.amount > 0}}">{{item.amount}}</text>
</view>
<text class="text-css">{{item.text}}</text>
</view>
</view>
</view>
可以请求后台,给定义的值重新绑定数据,例如给
onLoad: function () {
wx.setNavigationBarTitle({
title: "长安信保业务平台"
});
var platType = wx.getStorageSync("platType");
var that = this;
/**
* 获取用户信息
*/
// wx.getUserInfo({
// success: function (res) {
// var avatarUrl = 'userInfo.avatarUrl';
// var nickName = 'userInfo.nickName';
// var userName = 'userInfo.userName';
// that.setData({
// [avatarUrl]: res.userInfo.avatarUrl,
// [nickName]: res.userInfo.nickName,
// })
// }
// });
//是否等了
var userId = wx.getStorageSync('userId');
if(userId == "" || userId == undefined){
wx.redirectTo({
url: '../login/login'
});
return;
}
//获取报单条数
wx.request({
url: getApp().data.servsers +'/dataInterfaceForMobile/queryLoanCount.shtml',
data: {
userId: wx.getStorageSync('userId')
},
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
var msg = res.data.data[0].msg;
var userName = 'userInfo.userName';
var institutionName = 'userInfo.institutionName';
var businessArr = that.data.businessHide;
var othersArr = that.data.othersHide;
var arr = new Array();
var arr2 = new Array();
if(msg == "ok"){
//判断是查勘员还是管理员
if (platType == 1){
that.setData({
showID: 1,
business :arr,
'business[0].amount': res.data.data[0].examineCount,
'business[0].show': 'Y',
[userName]: res.data.data[0].userName,
[institutionName]: res.data.data[0].institutionName
})
} else if (platType == 2){
that.setData({
showID: 1,
'business[0].amount': res.data.data[0].carSurveyCount,
'business[1].amount': res.data.data[0].houseSurveyCount,
'business[2].amount': res.data.data[0].jdCount,
'business[3].amount': res.data.data[0].examineCount,
'business[4].amount': res.data.data[0].qzCount,
'business[5].amount': res.data.data[0].zgCount,
'business[0].show': 'Y',
'business[1].show': 'Y',
'business[2].show': 'Y',
'business[3].show': 'Y',
'business[4].show': 'Y',
'business[5].show': 'Y',
[userName]: res.data.data[0].userName,
[institutionName]: res.data.data[0].institutionName
})
} else if (platType == 3){
//移除数组
arr.push(businessArr[0]);
arr.push(businessArr[1]);
arr.push(businessArr[2]);
arr.push(businessArr[5]);
arr2.push(othersArr[2]);
that.setData({
showID: 1,
business: arr,
others: arr2,
'business[0].amount': res.data.data[0].carSurveyCount,
'business[1].amount': res.data.data[0].houseSurveyCount,
'business[2].amount': res.data.data[0].jdCount,
'business[3].amount': res.data.data[0].zgCount,
'business[0].show': 'Y',
'business[1].show': 'Y',
'business[2].show': 'Y',
'business[3].show': 'Y',
[userName]: res.data.data[0].userName,
[institutionName]: res.data.data[0].institutionName,
})
}
}else{
wx.redirectTo({
url: '../login/login'
});
return;
}
}
})
},
4.提交表单获取表单中的值 获取表单的值需要使用<form></form> 把需要提交的信息包起来,不然拿不到数据.
页面:
<form bindsubmit="bindFormSubmit">
<block wx:if="{{currentPage == 1}}">
<view class="weui-cell">
<view class="weui-cell__hd">
<text class="weui-label">行驶里程</text>
</view>
<view class="weui-cell__bd">
<input class="weui-input" value='{{loanMsg.mileage}}' name="mileage" type="text" placeholder="请输入行驶里程" />
</view>
<view class="weui-cell__ft">
<text>万公里</text>
</view>
</view>
<view class="weui-cell">
<view class="weui-cell__hd">
<text class="weui-label">车身颜色</text>
</view>
<view class="weui-cell__bd">
<input class="weui-input" value='{{loanMsg.car_color}}' name="car_color" type="text" placeholder="请输入车身颜色" />
</view>
</view>
<view class="weui-cell">
<view class="weui-cell__hd">
<text class="weui-label">排量</text>
</view>
<view class="weui-cell__bd">
<input class="weui-input" value='{{loanMsg.displacement}}' name="displacement" type="text" placeholder="请输入汽车排量" />
</view>
</view>
<view class="weui-cell weui-cell_access">
<view class="weui-cell__hd">
<text class="weui-label">年检到期日</text>
</view>
<view class="weui-cell__bd weui-select">
<picker mode="date" value="{{NJdate}}" start="2001-01-01" end="2019-09-01" bindchange="yearDate">
<view class="picker"> {{NJdate}}</view>
</picker>
</view>
</view>
<view class="weui-cell weui-cell_access">
<view class="weui-cell__hd">
<text class="weui-label">交强险到期日</text>
</view>
<view class="weui-cell__bd weui-select">
<picker mode="date" value="{{JQdate}}" start="2001-01-01" end="2019-09-01" bindchange="trafficDate">
<view class="picker"> {{JQdate}}</view>
</picker>
</view>
</view>
<view class="page_hd">
<button size="default" type="primary" class="btn-hover" data-id="3" bindtap="pageTap">确认提交</button>
</view>
</form>
js:
bindFormSubmit: function (e) {
var that = this;
var val = e.detail.value;
var currentPage = e.detail.target.dataset.id;
var userCar = this.data.userCar;
var business_code = this.data.loanMsg.business_code;
var car_type_brand = this.data.car_type_brand;
var car_type_series = this.data.car_type_series;
var car_type = this.data.car_type;
var userDate = this.data.userDate;
var mileage = val.mileage;
var car_color = val.car_color;
var displacement = val.displacement;
var NJdate = this.data.NJdate;
var JQdate = this.data.JQdate;
var car_valuation = val.car_valuation;
var next_year_car_valuation = val.next_year_car_valuation;
var remark = val.remark;
if (userCar == '请选择车型') {
util.showMsg("请选择车型", 1, 'none');
return;
}
if (userDate == '请选择首次上牌日期') {
util.showMsg("请选择首次上牌日期", 1, 'none');
return;
}
if (mileage.length == 0) {
util.showMsg("请填写行驶里程", 1, 'none');
return;
}
if (car_color.length == 0) {
util.showMsg("请填写车身颜色", 1, 'none');
return;
}
if (displacement.length == 0) {
util.showMsg("请填写排量", 1, 'none');
return;
}
if (NJdate == '请选择年检到期日') {
util.showMsg("请选择年检到期日", 1, 'none');
return;
}
if (JQdate == '请选择交强险期日') {
util.showMsg("请选择交强险期日", 1, 'none');
return;
}
if (car_valuation.length == 0) {
util.showMsg("请填写车辆估值", 1, 'none');
return;
}
if (next_year_car_valuation.length == 0) {
util.showMsg("请填写下一年估值", 1, 'none');
return;
}
that.setData({
showID: 0
});
wx.request({
url: getApp().data.servsers + "dataInterfaceSurveyCarForMobile/saveSurveyCarUi.shtml",
data: {
userId: wx.getStorageSync('userId'),
business_code: business_code,
car_type_brand: car_type_brand,
car_type_series: car_type_series,
car_type: userCar,
buy_car_time: userDate,
mileage: mileage,
car_color: car_color,
displacement: displacement,
NJdate: NJdate,
JQdate: JQdate,
car_valuation: car_valuation,
next_year_car_valuation: next_year_car_valuation,
remark: remark
},
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
var msg = res.data.data[0].msg;
var fileUrlListResult = res.data.fileUrlList;
var videoList = res.data.videoList;
var userlList = res.data.userlList[0];
var imgUrls = that.data.imgUrls;
if (msg == "ok") {
for (var index in fileUrlListResult) {
that.data.imgUrls[index] = fileUrlListResult[index].url;
}
that.setData({
fileUrlList: fileUrlListResult,
['userMsg.userName']: userlList.userName,
['userMsg.id_no']: userlList.id_no,
['userMsg.phoneNo']: userlList.phoneNo,
videoSrc: videoList,
currentPage: 2,
showID : 1
});
}
}
})
},
5.小程序图片上传
//选择图片
imageFun: function (e) {
var business_code = e.currentTarget.dataset.business_code;
var pg_business_code = e.currentTarget.dataset.pg_business_code;
var filename = e.currentTarget.dataset.filename;
var name = e.currentTarget.dataset.name;
var that = this;
wx.chooseImage({
count: 9, // 默认9
sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['camera','album'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
var tempFilePaths = res.tempFilePaths; // 返回选定照片的本地ID列表,tempFilePaths可以作为img标签的src属性显示图片
var size = tempFilePaths.length;
for (var i = 0; i < size; i++) {
wx.showLoading({
title: '正在上传',
});
wx.uploadFile({
url: getApp().data.servsers + "dataInterfaceForMobile/saveFile.shtml",
filePath: tempFilePaths[i],
name: 'files',
formData: {
'business_code': business_code,
'pg_business_code': pg_business_code,
'userId': wx.getStorageSync('userId'),
'class_': filename,
'subclass_': name,
'business_type': 'car_survey'
},
success: function (res) {
var data = res.data;
var result = JSON.parse(data);
var fileUrlListResult = result.fileUrlList[0];
if (fileUrlListResult.msg == "success") {
wx.hideLoading();
wx.showToast({
title: "上传成功",
icon: 'none',
duration: 1000
});
//回显图片
that.data.fileUrlList.push(fileUrlListResult);
that.setData({
fileUrlList: that.data.fileUrlList,
showID : 1
});
} else {
wx.showToast({
title: "上传失败",
icon: 'none',
duration: 1000
});
}
}
})
}
}
});
},
6.预览图片
//定义一个数组用来储存图片
Page({
/**
* 页面的初始数据
*/
data: {
//图片附件
imgUrls: [""],
},
});
//显示图片
showImg: function (option) {
var url = option.currentTarget.dataset.url;//点击图片所获取的url地址
var imgUrls = this.data.imgUrls;
imgUrls.push(url);//将url地址添加到图片数组中,可以滑动查看下一张
wx.previewImage({
current: url,
urls: imgUrls
});
},
7.上传视频
//上传视频
uploadVideo: function (e) {
var that = this;
var videoSrcList = that.data.videoSrc;
var business_code = e.currentTarget.dataset.business_code;
wx.chooseVideo({
sourceType: ['camera','album'],
maxDuration: 30,
camera: 'back',
success: function (res) {
var tempFilePath = res.tempFilePath;
var duration = res.duration;
//视频上传只能30s内
if (duration > 30) {
util.showMsg("只能上传30s以内视频", 1, "none");
return;
}
wx.showLoading({
title: '正在上传',
});
wx.uploadFile({
url: getApp().data.servsers + "dataInterfaceForMobile/saveFile.shtml",
filePath: tempFilePath,
name: 'files',
formData: {
'business_code': business_code,
'userId': wx.getStorageSync('userId'),
'class_': '验车视频',
'subclass_': '验车视频'
},
success: function (res) {
var data = res.data;
var result = JSON.parse(data);
var fileUrlListResult = result.fileUrlList[0];
that.data.videoSrc.push(fileUrlListResult);
if (fileUrlListResult.msg == "success") {
wx.hideLoading();
wx.showToast({
title: "上传成功",
icon: 'none',
duration: 1000
});
//回显视频
that.setData({
videoSrc: that.data.videoSrc,
showID : 1
});
} else {
wx.showToast({
title: "上传失败",
icon: 'none',
duration: 1000
});
}
}
})
}
})
},
8.弹出提示框
//js要引入utl包
var util = require('../../utils/util.js');
wx.showToast({
title: '删除成功',
icon: 'none',
duration: 1000
});
//微信util有js提示,和上面效果一样
util.showMsg("只能上传30s以内视频", 1, "none");
//提示用户是否删除
wx.showModal({
title: '提示',
content: '是否删除?',
success: function(res) {
if (res.confirm) {
console.log('用户点击确定')
} else if (res.cancel) {
console.log('用户点击取消')
}
}
});
9.页面循环展示数据 这里是循环展示图片
<view id="carYbimg" class="weui-uploader__file img_div" wx:for='{{fileUrlList}}' wx:if="{{item.accessory_type_subclass=='小区内景'}}">
<image class="slide-image" src="{{item.url}}" data-url="{{item.url}}" bindtap="showImg" />
<i class="weui-icon-del" bindtap="deleteImg" data-id="{{item.id}}">×</i>
</view>
</view>
10.最后可以公众号配置菜单,直接跳小程序,前提是公众号关联了该小程序
{
"button": [{
{
"name": "业务跟进",
"sub_button": [{
"type": "miniprogram",
"name": "业务跟进",
"url": "http://mp.weixin.qq.com",
"sub_button": [],
"appid": "wx8a15579ffeba70bb",
"pagepath": "pages/index/index"
}
]
}
]
}