我是因为公司项目接触WeUI的,实话说刚开始的时候并不顺。我最先看的是jquery weui然后偶然发现了weui+。这两种都是在WeUI基础上的拓展,但我经过一段时间的使用,觉得简单的微信公众平台页面的开发还是使用WeUI更为方便。
那么我就来分享下我的学习体会:WeUI的官方简介说WeUI is an WeChat-like UI framework officially designed by the WeChat Design Team, tailor-made for WeChat Web development, in order to improve and standardize the experience for WeChat users.实际上它就是一个为微信开发量身定做的组件库。然而我不太理解网上真正按照官方文档和用官方组件库的并不多。这里先发一下官方文档链接:WeUI的GitHub地址,WeUI.js的GitHub地址。大家可以自行参考。
好,我正式开始我使用的组件的介绍和自己项目的分享了。
1)picker(选择器)
这是我觉得比较美观和体验感好的选择器,jquery weui的select选择器实在让我感到违和。如果是固定值单列的选择器是比较简单的。1)第一个就是picker(选择器)
这是我觉得比较美观和体验感好的选择器,jquery weui的select选择器实在让我感到违和。如果是固定值单列的选择器是比较简单的。前台就是简单的input控件外面套个select箭头。Html:
<div class="weui-cell weui-cell_select" style="width: 100%;">
<div class="weui-cell__hd">
<label class="weui-form-preview__label"> 区域分划</label>
</div>
<div class="weui-cell__bd">
<input class="weui-input" name="select1" id="selectAdminarea" placeholder="请选择区域分划" readonly="readonly"></input>
</div>
</div>
而js部分就是定义好label和value值后,我们的重点就是onChange(),onConfirm(),onClose()的方法了。js:
weui.picker([
{
label: '新成路街道',
value: '310114001'
}, {
label: '真新街道',
value: '310114002'
}, {
label: '菊园新区管委会',
value: '310114001'
}, {
label: '嘉定镇街道',
value: '310114002'
}, {
label: '南翔镇',
value: '310114001'
}, {
label: '安亭镇',
value: '310114103'
}
], {
defaultValue: ['310114001'],
onChange: function (result) {
// console.log(result);
},
onConfirm: function (result) {
$("#selectAdminarea").val(result[0].label);
selectArea = result[0].value;
// console.log(selectArea);
},
id: 'selectAdminarea'
});
注意点:因为你js的选择的值还需要赋值给你所需要赋值的地方即input框所以有必要在确认方法里加$("#inputId").val(选择的返回值)。
但如果我们需要把从后台获取数据绑定在选择框上呢?并且我们往往会有多级选择的情况出现,就比如地址的选择:城市->街镇那样
var resJson = new Array();
//ajax远程加载初始化问题类别下拉框选项
myajax = $.ajax({
url: rootUrl + "casetype/getCaseType",
type: "get",
contentType: "application/json",
data: {
"parentCodes": "1,2",
"levelType": "2"
},
//traditional: true,
success: function(res) {
if (res.data != null) {
var data = res.data;
var jsondata = eval('(' + data + ')');
var resdata = jsondata.data;
var tempcode = new Array();
var tempname = new Array();
var tmp = new Array();
var index = 0;
for (var i = 0; i < resdata.length; i++) {
if (tempcode.indexOf(resdata[i].parent.code) == -1) {
tempcode.push(resdata[i].parent.code);
tempname.push(resdata[i].parent.name);
++index;
}
}
for (var j = 0; j < index; j++) {
var childoption = "";
var childarray = new Array();
var option = "";
for (var i = 0; i < resdata.length; i++) {
if (resdata[i].parentCode == tempcode[j]) {
childoption = {
"label": resdata[i].name,
"value": resdata[i].code
};
childarray.push(childoption);
option = {
"label": tempname[j],
"value": tempcode[j],
"children": childarray
};
}
}
resJson.push(option);
}
}
},
error: function(msg) {
weui.alert("出错了!" + msg);
}
});
$.when(myajax).done(function() {
weui.picker(resJson, {
onChange: function onChange(result) {
console.log(result);
},
onConfirm: function onConfirm(result) {
$("#selectQues").val(result[1].label);
selectType = result[1].value;
console.log(selectType);
},
});
});
注意点:这里的选择器绑定的后台数据所以应该先执行myajax里的请求内容,确保后台数据取出绑定在选择器上。但因为ajax请求默认是异步的,所以我就写了$.when(myajax).done(function(){});就是等myajax执行完后执行picker方法。
2) uploader(上传组件)
我做的这个图片上传,几经波折,我原先用的jquery weui压缩十分复杂,并且ios竖屏拍摄的图片还需要旋转。真的劳神劳时。但我后来发现weui本身的上传组件并不存在这种问题。所以具体问题大家可以使用了以后看看,我现在为止还没出现过什么问题。Html:
<div class="weui-gallery" id="gallery">
<span class="weui-gallery__img" id="galleryImg"></span>
<div class="weui-gallery__opr">
<a href="javascript:" class="weui-gallery__del">
<i class="weui-icon-delete weui-icon_gallery-delete"></i>
</a>
</div>
</div>
<div class="weui-cell" id="uploader">
<div class="weui-cell__bd">
<div class="weui-uploader">
<div class="weui-uploader__hd">
<span class='f-red'>*</span>
<p class="weui-uploader__title">图片上传</p>
<div class="weui-uploader__info"><span id="uploadCount">0</span>/9</div>
</div>
<div class="weui-uploader__bd">
<ul class="weui-uploader__files" id="uploaderFiles"></ul>
<div class="weui-uploader__input-box">
<input id="uploaderInput" class="weui-uploader__input" type="file" accept="image/*" multiple name="file"/>
</div>
</div>
</div>
</div>
</div>
注意点: 前面的gallery是带删除按钮的图片预览,这里和图片上传搭配使用方便用户浏览。还有就是因为我们是多张图片上传所以要加multiple代表多张。然后因为要既可以拍照又可以相册上传所以要加accept="image/*"。接下来就是js部分:
var uploadCount = 0;
var uploadCustomFileList = [];
var countA= [];
var uploadCountDom = document.getElementById("uploadCount");
weui.uploader('#uploader', {
url: rootUrl + "file/upload/",
auto: false,
type: 'file',
fileVal: 'fileVal',
compress: {
width: 1600,
height: 1600,
quality: .8
},
onBeforeQueued: function(files) {
if(["image/jpg", "image/jpeg", "image/png", "image/gif"].indexOf(this.type) < 0){
weui.alert('请上传图片');
return false; // 阻止文件添加
}
if(this.size > 10 * 1024 * 1024){
weui.alert('请上传不超过10M的图片');
return false;
}
if (files.length > 9) { // 防止一下子选择过多文件
weui.alert('最多只能上传9张图片,请重新选择');
return false;
}
++uploadCount;
uploadCountDom.innerHTML = uploadCount;
},
onQueued: function(){
console.log(this);
uploadCustomFileList.push(this);
},
onBeforeSend: function(data, headers){
console.log(this, data, headers);
},
onProgress: function(procent){
console.log(this, procent);
},
onSuccess: function (ret) {
console.log(this, ret);
countA.push(ret.data)
},
onError: function(err){
console.log(this, err);
}
});
var $gallery = $("#gallery"), $galleryImg = $("#galleryImg"),
$uploaderFiles = $("#uploaderFiles");
var index; //第几张图片
//点开图片
$uploaderFiles.on("click", "li", function(){
index = $(this).index();
$galleryImg.attr("style", this.getAttribute("style"));
$gallery.fadeIn(100);
});
//关闭图片
$gallery.on("click", function(){
$gallery.fadeOut(100);
});
//删除图片
$(".weui-gallery__del").click(function(e) {
var target = e.target;
var id = target.getAttribute('data-id');
for (var i = 0, len = uploadCustomFileList.length; i < len; ++i) {
var file = uploadCustomFileList[i];
if (file.id == id) {
index = i;
break;
}
}
if (index) uploadCustomFileList.splice(index, 1);
$uploaderFiles.find("li").eq(index).remove();
uploadCount = uploadCount-1;
uploadCountDom.innerHTML = uploadCount;
});
注意点:因为我们需要保存到后台,所以我们得设置那个fileVal就是文件上传域的name与后台接收的请求参数名得一直,否则值会一直传不到。还有atuo代表是否自动上传,如果自动上传的话代表传一张图片就会往后台传一张,如果要统一上传就可以选false,compress就是压缩的配置了。至于后台本人用的java以下仅供参考:
@Api(value = "文件上传下载接口", tags = {"文件上传下载接口"})
@RequestMapping("/file")
@RestController
public class fileController {
@PostMapping("/upload")
public ResponseModel upload(@RequestParam("fileVal") MultipartFile file) {
try {
if (file.isEmpty()) {
return new ResponseModel(true, ResponseStatus.OPERATE_FAIL.getCode(), ResponseStatus.OPERATE_FAIL.getMessage(), "文件为空");
}
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
// 设置文件存储路径
//String filePath = "Upload";
String newFileName = UUID.randomUUID().toString();
String virpath = System.getProperty("user.dir") + "/" + ConstsHelper.Upload_filePath + "/" + newFileName + suffixName;
// String path = new File(System.getProperty("user.dir") + "/" + ConstsHelper.Upload_filePath).getAbsolutePath() + "/" + newFileName + suffixName;
String path = virpath;
File dest = new File(path);
// 检测是否存在目录
dest.getParentFile().mkdirs();// 不存在创建文件夹
file.transferTo(dest);// 文件写入
String uid = "", name = "", status = "",url = "", type = "";
uid = newFileName;
name = newFileName + suffixName;
status = "success";
url = virpath.substring(virpath.lastIndexOf("\\")+1);
type = "image";
InetAddress address = InetAddress.getLocalHost();
String hostAddress = address.getHostAddress();
String nzfile = "";
url = "http://" + hostAddress.toString() + "/" + url;
nzfile = "{\"uid\":\"" + uid + "\",\"name\":\"" + name + "\",\"status\":\"" + status + "\",\"url\":\"" + url + "\",\"type\":\"" + type + "\"}";
return new ResponseModel(true, ResponseStatus.SUCCESS.getCode(), ResponseStatus.SUCCESS.getMessage(), nzfile);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new ResponseModel(true, ResponseStatus.OPERATE_FAIL.getCode(), ResponseStatus.OPERATE_FAIL.getMessage());
}
}
注意点:还是得提一下RequestParam("前台文件上传域name")很重要,不传会一直接收不到文件。还有就是虽然前台是多张图片上传的,但传给后台是单个接收的,我并不是自动上传的所以在单个保存到服务器后我会进行拼接这个图片字符串然后统一传给我要传的接口或者数据库。
3)confirm(确认)
顾名思义就是按确定的时候提示作用,是跳出框,没有html代码只有js部分,仅供参考:
weui.confirm('是否确认提交', {
title: '提示框',
buttons: [{
label: '取消',
type: 'default',
onClick: function () {
}
}, {
label: '确定',
type: 'primary',
onClick: function () {
var promise = new Promise(function (resolve, reject) {
uploadCustomFileList.forEach(function (file) {
file.upload();
});
setInterval(function () {
if (uploadCustomFileList.length == countA.length) {
resolve()
}
}, 0);
});
promise.then(function() {
var postData = {
"reportID": formateDateAndTimeToString(new Date()),
"person": $('#inputPer').val(),
"telphone": $('#inputTel').val(),
"adminarea": selectArea,
"questionType": selectType,
"address": $('#atcity').val(),
"addressX":$('#addressX').text(),
"addressY":$('#addressY').text(),
"questionDesc": $('#textareaDesc').val()
};
if (postData.questionType == '') {
weui.alert("请填写问题类别");
return;
}
if (postData.address == '') {
weui.alert("请填写发现地址");
return;
}
postData.attachment = "[" + countA.join(',') + "]";
$.ajax({
type: 'Put',
url: rootUrl + "report/addReport",
data: JSON.stringify(postData),
contentType: 'application/json;charset=UTF-8',
success: function(res) {
var data = eval('(' + res.message + ')');
console.log(data.message.indexOf("成功"));
if (data.message.indexOf("成功") != -1) {
window.location.href = localUrl + "page/msgsuccess.html";
} else {
weui.alert(data.message);
}
},
error: function() {
weui.alert("网站出现异常");
}
});
})
}
}]
});
注意点:这个控件相对很简单只需要弄清楚取消和确定两个事件就可以了。
以上纯属个人使用心得如果有任何错误欢迎指出,谢谢!