小程序组件使用记录
以下用上传图片为例,组件目录为/component/uploadImgs
假设图片上传后台,后台返回的值都是图片路径 例:/uploads/20200224/d5d8680cada63c6faa2f7198a43953dc.jpg
1. 组件写法
- js文件中(/component/uploadImgs/uplods.js)
//仅作为示例
Component({
//这里接收父组件wxml标签中传递过来的值
properties: {
files: {
type: Array,
value: []
},
maxFileCount: { //允许最多1张图片
type: Number,
value: 1
},
maxSize: {//允许最大1.4MB
type: Number,
value: 1.4
},
uploadUrl: {//图片上传的后台url地址
type: String,
value: 'uploads/cardImg'
}
},
//初始化值
data: {
// 图片所在的主机地址
'domain': 'https://imghost.example.com/'
},
methods: {
__chooseImgs: function(e) {
var that = this;
//图片大小限制
var maxSize = this.data.maxSize * 1000000;
wx.chooseImage({
count: that.data.maxFileCount - that.data.files.length,
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function(res) {
//do something,将上传的图片地址存入files变量数组中
// 这里是子组件调用父组件方法
that.triggerEvent('us',params);
}
})
},
........
........
........
/*************供外部调用接口*******************/
getFiles: function() {
return this.data.files;
}
}
})
- wxml文件中(/component/uploadImgs/uplods.wxml)
// 仅作为示例
<view class="cu-form-group" style="padding: 20rpx 15rpx;">
<view class="grid col-4 grid-square flex-sub">
<view class="bg-img" wx:for="{{files}}" wx:key="*this" style="width:100%;height:200px;">
<image src='{{domain}}{{item}}' mode='aspectFill' bindtap="__previewImage"></image>
<view class="cu-tag bg-red" catchtap="__deleteImage" style="height: 36px;" data-index="{{index}}">
<text class="cuIcon-close"></text>
</view>
</view>
<view class="solids" bindtap="__chooseImgs" wx:if="{{files.length < maxFileCount}}" style="width:100%;height:200px;background:rgb(254,252,255);padding-top:30px;">
<text class="cuIcon-vipcard" style="font-size:80px;color:grey;position:relative"></text>
<view style="font-size:15px;text-align:center;" class="justify-center">请上传你的证件照</view>
</view>
</view>
</view>
2. 使用组件(小程序页面中)
2.1 json文件中引用component
"navigationBarTitleText": "这是页面标题",
"usingComponents": {
// 定义组件名称,及组件目录
"upload": "/component/uploadImgs/upload",
}
2.2 wxml中使用组件
// 传值给子组件时,直接在 标签中写入key=value即可,下方示例files maxSize maxFileCount
// 有时候我们想让子组件来调用父组件中的方法,就用到了bind, us uss 都是自定义
//bind是作用是让 子组件 来调用 父组件 的定义的uss方法,没有需求的话可以删除这个bind 往下看
<upload bind:us="uss" id='card_image' files='{{card_image}}' maxSize="1" maxFileCount='{{max_card_image}}'>
</upload>
2.3 js文件中初始化
data: {
//上传图片的地址,如果是页面编辑 ,把图片url放入此数组中即可
card_image: [],
//图片最多上传几张
max_card_image: 1,
}
onReady: function () {
//获得upload组件,后续直接用upload调用组件方法
this.card_image_component = this.selectComponent("#card_image");
}
// 调用组件中的getFiles方法来获取已经上传的图片地址,并用逗号连接成字符串
// 通用来说,就是获取组件中的值
var card_image = this.card_image_component.getFiles().join(',');
uss(e){
var that = this;
//这里获取到子组件传过来的值,detail中就是组件给的值
var cr = e.detail.card_res;
//以下是示例,请按照自己的需求来写
if(cr.code == 1){
//do something
}else{
//do something
}
}
END