components/chooseMedia/chooseMedia.wxml
<view class="ipt">
<image class="close1" src="/static/image/close1.png" bindtap="closeBtn" wx:if="{{isShow}}">image>
<image class="imgz" src="{{zwImg}}" wx:if="{{!isShow}}" bindtap="chooseMedia">image>
<image class="imgz" src="{{bank_img}}" wx:if="{{isShow}}" mode="aspectFill">image>
view>
components/chooseMedia/chooseMedia.js
// components/chooseMedia/chooseMedia.js
Component({
/**
* 组件的属性列表
*/
properties: {
zwImg:{ //提交图片的默认图片
type:String,
value:'/static/image/jia.png'
},
bank_img:{ //上传的图片路径
type:String,
value:''
},
isShow:{
type:Boolean,
value:false
}
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
// 选择图片
chooseMedia() {
wx.chooseMedia({
count: 1,
mediaType: ['image'],
sourceType: ['album', 'camera'],
maxDuration: 30,
camera: 'back',
success: (res) => {
let tempFilePath = res.tempFiles[0].tempFilePath;
this.uploadFile(tempFilePath)
}
})
},
// 上传图片到服务器
uploadFile(tempFilePath) {
wx.showLoading();
wx.uploadFile({
filePath: tempFilePath,
name: 'file',
url: getApp().globalData.url + 'common/upload',
formData: {
'data': 'bank_img'
},
success: (res) => {
wx.hideLoading();
const bank_img = JSON.parse(res.data).img; //把数据字符串转变成对象
if(bank_img){
this.setData({
bank_img:bank_img,
isShow:true
})
}
this.triggerEvent('chooseMedia', bank_img)
}
})
},
// 删除上传图片
closeBtn(){
this.setData({
isShow:false,
bank_img:''
})
}
}
})
components/chooseMedia/chooseMedia.wxss
/* components/chooseMedia/chooseMedia.wxss */
.imgz{
width: 140rpx;
height: 140rpx;
}
.close1{
width: 50rpx;
height: 50rpx;
position: absolute;
margin-left: 100rpx;
margin-top: -20rpx;
}
在需要引进的json中引用组件:
"usingComponents": {
"chooseMedia":"/components/chooseMedia/chooseMedia"
},
在wxml中调用组件:
<chooseMedia bindchooseMedia="chooseMedia" bank_img="{{infos.card_img}}" isShow="{{isShow}}">chooseMedia>
在js中调用方法存入数据和发送给子组件数据:
data: {
user_id:'',
isShow:false,
infos:{}
},
// 获取信息
async getInfos(){
let infos = await return_method_desc();
this.setData({
infos:infos.data,
isShow:true
})
},
// 获取子组件数据
chooseMedia(e){
this.setData({
['infos.card_img']: e.detail
})
},