uni-id-pages-x-avatar.uvue 6.4 KB
Newer Older
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
1 2 3 4 5 6
<template>
	<view class="avatar-box-root">
		<!-- #ifdef MP-WEIXIN -->
		<button open-type="chooseAvatar" @chooseavatar="bindchooseavatar" @click="uploadAvatarImg" class="box"
			:class="{'showBorder':border}" :style="{width,height,lineHeight:height}">
		<!-- #endif -->
7 8 9 10
		<!-- #ifndef MP-WEIXIN -->
		<view @click="uploadAvatarImg" class="box" :class="{'showBorder':border}"
			:style="{width,height}">
		<!-- #endif -->
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
11

A
Anne_LXM 已提交
12
			<!-- {{avatar_file!.getString("url")}} -->
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
      <cloud-image v-if="avatar_file != null" :src="avatar_file!.getString('url')" :width="width" :height="height"></cloud-image>
			<image v-else-if="readOnly" class="default-avatarUrl" src="@/uni_modules/uni-id-pages-x/static/default-avatar.png" mode="widthFix"></image>
      <view v-else class="upload-img-icon">
				<uni-id-pages-x-icons :size="35" color="#eee" type="jiahao"></uni-id-pages-x-icons>
			</view>

			<!-- #ifndef MP-WEIXIN -->
			</view>
			<!-- #endif -->
		<!-- #ifdef MP-WEIXIN -->
		</button>
		<!-- #endif -->
	</view>
</template>

<script>
雪洛's avatar
雪洛 已提交
29
	import { state, mutations } from '@/uni_modules/uni-id-pages-x/store.uts';
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
30
	/**
A
Anne_LXM 已提交
31
	* uni-id-pages-x-avatar
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
	* @description 用户头像组件
	* @property {String} width	图片的宽,默认为:50px
	* @property {String} height	图片的高,默认为:50px
	*/
	export default {
		name: "uni-id-pages-x-avatar",
		data() {
			return {
				isPC: false
			}
		},
		props: {
			//头像图片宽
			width: {
				type: String,
				default: "50px"
			},
			//头像图片高
			height: {
				type: String,
				default: "50px"
			},
			border: {
				type: Boolean,
				default: false
			},
      readOnly: {
				type: Boolean,
				default: false
			}
		},
		mounted() {
			// #ifdef WEB
			this.isPC = !['ios', 'android'].includes(uni.getSystemInfoSync().platform);
			// #endif
		},
		computed: {
			hasLogin() : boolean {
雪洛's avatar
雪洛 已提交
70
				return state.isLogin as boolean
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
			},
			userInfo() : UTSJSONObject {
				return state.userInfo
			},
			avatar_file() : UTSJSONObject | null {
				return this.userInfo.getJSON("avatar_file")
			}
		},
		methods: {
			setAvatarFile() {//avatar_file : AvatarFile
				// 使用 clientDB 提交数据
				// mutations.updateUserInfo({avatar_file})
			},
			bindchooseavatar() {
				// res
				// let avatarUrl = res.detail.avatarUrl
				// let avatar_file = {
				// 	extname: avatarUrl.split('.')[avatarUrl.split('.').length - 1],
				// 	name:'',
				// 	url:''
				// }
				// //上传到服务器
				// let cloudPath = this.userInfo._id + '' + Date.now()
				// avatar_file.name = cloudPath
				// try{
				// 	uni.showLoading({
				// 		title: "更新中",
				// 		mask: true
				// 	});
				// 	let {
				// 		fileID
				// 	} = await uniCloud.uploadFile({
				// 		filePath:avatarUrl,
				// 		cloudPath,
				// 		fileType: "image"
				// 	});
				// 	avatar_file.url = fileID
				// 	uni.hideLoading()
				// }catch(e){
				// 	console.error(e);
				// }
				// console.log('avatar_file',avatar_file);
				// this.setAvatarFile(avatar_file)
			},
			uploadAvatarImg() {
        if(this.readOnly){
A
Anne_LXM 已提交
117
          return
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
        }
				// #ifdef MP-WEIXIN
				return // 微信小程序走 bindchooseavatar方法
				// #endif
				// #ifndef MP-WEIXIN
				// if(!this.hasLogin){
				// 	uni.navigateTo({
				// 		url:'/uni_modules/uni-id-pages-x/pages/login/login-withoutpwd'
				// 	})
				//       return
				// }
				const crop : ChooseImageCropOptions = {
					quality: 100,
					width: 600,
					height: 600,
					resize: true
				};
				uni.chooseImage({
					count: 1,
					crop,
A
Anne_LXM 已提交
138
					success: (res) => {
139
						console.log('res', res);
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
140 141
						let tempFiles = res.tempFiles as UTSJSONObject[];
						let tempFile = tempFiles[0];
A
Anne_LXM 已提交
142 143
            let tempFileName = tempFile['name'] as string | null
						let tempFilePath = tempFile['path'] as string | null
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
144 145 146 147 148 149 150
						if (tempFileName == null) {
							tempFileName = ""
						}
						if (tempFilePath == null) {
							tempFilePath = ""
						}
						let avatar_file = {
A
Anne_LXM 已提交
151
							// #ifdef WEB
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
152 153
							extname: tempFileName.split(".")[tempFileName.split(".").length - 1],
							// #endif
A
Anne_LXM 已提交
154
							// #ifndef WEB
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
155 156 157 158 159
							extname: tempFilePath.split(".")[tempFilePath.split(".").length - 1],
							// #endif
							name: tempFileName,
							url: tempFilePath
						} as UTSJSONObject
A
Anne_LXM 已提交
160
						// console.log('avatar_file', avatar_file);
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
161 162 163 164 165

						let filePath = res.tempFilePaths[0]
						//非app端剪裁头像,app端用内置的原生裁剪
						// #ifndef UNI-APP-X
						filePath = await new Promise((callback) => {
A
Anne_LXM 已提交
166
							// #ifdef WEB
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
							if (!this.isPC) {
								callback(filePath)
							}
							// #endif

							uni.navigateTo({
								url: '/uni_modules/uni-id-pages-x/pages/userinfo/cropImage/cropImage?path=' +
									filePath + `&options=${JSON.stringify(crop)}`,
								animationType: "fade-in",
								events: {
									success: url => {
										callback(url)
									}
								},
								complete(e) {
									// console.log(e);
								}
							});
						})
						// #endif
						let _id = this.userInfo["_id"] as string
188
            // console.log("id",_id)
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
189 190 191 192
						// if(_id != null){
						//   _id = "" as string
						// }
						let cloudPath = _id + '' + Date.now()
193
            avatar_file['name'] = cloudPath
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
194 195 196 197 198 199 200 201
						uni.showLoading({
							title: "更新中",
							mask: true
						});
						uniCloud.uploadFile({
							filePath,
							cloudPath,
						})
A
Anne_LXM 已提交
202
							.then(function (res) {
203
                avatar_file['url'] = res.fileID
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
204 205
								mutations.updateUserInfo({ avatar_file } as UTSJSONObject)
							})
A
Anne_LXM 已提交
206
							.catch(function (err : any | null) {
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
207 208 209 210 211 212 213 214 215 216
								const error = err as UniCloudError
								uni.showModal({
									content: '上传失败,' + error.errMsg,
									showCancel: false
								});
								console.error(error);
							}).finally(() => {
								uni.hideLoading()
							})
					},
A
Anne_LXM 已提交
217
					fail:(err)=>{
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230 231
						console.error('chooseImage fail: ', err)
						uni.showModal({
							content: '失败,' + err.errMsg,
							showCancel: false
						});
					}
				})
				// #endif
			}
		}
	}
</script>

<style>
A
Anne_LXM 已提交
232 233 234 235
  .default-avatarUrl{
    width:44px;
    height:44px;
  }
DCloud_JSON's avatar
init  
DCloud_JSON 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
	.avatar-box-root {
		background-color: #fff;
	}

	.box {
		overflow: hidden;
		padding: 0;
	}

	.chooseAvatar {
		/* #ifndef UNI-APP-X */
		display: inline-block;
		box-sizing: border-box;
		/* #endif */
		border-radius: 100px;
		text-align: center;
		padding: 1px;
	}

	.upload-img-icon {
		border: 1px dotted #c8c8c8;
		width: 55px;
		height: 55px;
		justify-content: center;
		align-items: center;
	}

	.showBorder {
		border: solid 1px #ddd;
	}
A
Anne_LXM 已提交
266
</style>