布局(在Element复制):
<template>
<div class="hello">
<el-upload class="avatar-uploader"
action="http://api.baxiaobu.com/index.php/home/v1/upload"
name="upfile"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<img :src="avatar" style="width: 100px;height: 100px;"/>
</div>
</template>
js:
<script>
import axios from "axios";
import cookies from 'js-cookie';
import qs from 'qs';
export default {
data() {
return {
imageUrl: '',
avatar: "",
};
},
methods: {
handleAvatarSuccess(res, file) {
this.imageUrl = URL.createObjectURL(file.raw);
console.log(this.imageUrl)
this.upimg(res.pic_url)
},
beforeAvatarUpload(file) {
},
getimg() {
var url = "http://api.baxiaobu.com/index.php/home/v1/getUserInfo"
var params = {
user_id: cookies.get('token')
}
params = qs.stringify(params) /*获取到字符串类型的token*/
axios.post(url, params).then((res) => {
this.avatar = res.data.userInfo.avatar
})
},
upimg(avatars) {
var url = "http://api.baxiaobu.com/index.php/home/v1/updateAvatar"
var params = {
user_id: cookies.get('token'),
avatar: avatars
}
params = qs.stringify(params)
console.log(params)
axios.post(url, params).then((res) => {
this.getimg()
})
}
},
created() {
this.getimg()
}
}
</script>
css样式(在Element复制):
<style scoped>
.hello {
width: 100%;
float: left;
height: 900px;
background: white;
}
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>