基于Vant 组件库+微信公众号开发文档
html部分
<div class="filelist">
<div class="boximg">
<div v-for="(item,index) in imgArr" :key="index" class="boximgInner">
<van-image width="100" height="100" :src="item" />
<van-icon class="delIco" name="close" @click="delImg(index)" />
</div>
<div class="uploader" @click="chooseImg" v-show="imgArr.length<9">
<i class="van-icon van-icon-plus van-uploader__upload-icon">
<!---->
</i>
</div>
</div>
</div>
js部分
import Vue from "vue";
import { Toast,} from "vant";
Vue.use(Toast);
export default {
data() {
return {
images: {
localId: [],
serverId: []
},
img_i: 0,
uploadimg: false,
imgArr: [],
imgIdsArr: []
}
},
methods:{
// 删除图片
delImg(index) {
this.imgArr.splice(index, 1);
this.imgIdsArr.splice(index, 1);
},
// 获取微信的sdk
signatureJSSDK() {
//var url = "http://zhsqtest.xyre.com/WeChatPublic/index.html";//后台需要此页面的url来生成参数
// var url = window.location.href.split('#')[0];//后台需要此页面的url来生成参数
var url = encodeURIComponent(window.location.href.split("#")[0]); //后台需要此页面的url来生成参数
this.$http
.get("/wechat/image/sign?url=" + url, {})
.then(res => {
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: res.data.appId, // 必填,公众号的唯一标识
timestamp: res.data.timestamp, // 必填,生成签名的时间戳
nonceStr: res.data.noncestr, // 必填,生成签名的随机串
signature: res.data.signature, // 必填,签名,见附录1
jsApiList: [
// 必填,需要使用的JS接口列表,所有JS接口列表见附录2
"chooseImage",
"previewImage",
"uploadImage",
"downloadImage",
"translateVoice"
]
});
console.log("微信签名", wx.config);
})
.catch(e => {
console.log("签名失败", e);
});
},
chooseImg(e) {
let that = this;
wx.ready(() => {
wx.chooseImage({
count: 9 - this.imgArr.length, // 最多可以选择的图片张数,默认9
sizeType: ["original", "compressed"], // original 原图,compressed 压缩图,默认二者都有
sourceType: ["album", "camera"], // album 从相册选图,camera 使用相机,默认二者都有
complete: function(res) {
console.log("chooseImage", res);
that.img_i = 0;
if (res.errMsg == "chooseImage:ok") {
that.images.localId = res.localIds;
if (that.images.localId.length > 0) {
setTimeout(that.upload, 100);
}
} else if (res.errMsg == "chooseImage:cancel") {
} else {
Toast("获取图片失败,请重新选择");
}
}
});
});
},
upload() {
let that = this;
wx.uploadImage({
localId: that.images.localId[that.img_i],
complete: function(res) {
that.img_i++;
if (res.errMsg == "uploadImage:ok") {
that.images.serverId.push(res.serverId);
that.uploadimg = true;
console.log("上传图片", res.serverId);
that.$http
.post("/wechat/image/saveImageToWx?mediaId=" + res.serverId)
.then(res => {
var objd = res.data.obj;
var src = objd.filePath;
that.imgArr.push(objd.filePath);
var fileId = objd.fileId;
that.imgIdsArr.push(fileId);
})
.catch(e => {
console("e" + e);
});
}
if (that.img_i < that.images.localId.length) {
setTimeout(that.upload, 100);
}
}
});
},
},
mounted(){
this.signatureJSSDK(); // 获取签名
}
}