vue封装-头像(照片上传)

 vue封装组件

<template>
  <el-upload :headers='headers' :action="baseFileUrl" :show-file-list="false" accept=".jpg,.png,.gif,.jpeg"
             :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
    <img v-if="value" :src="value" class="avatar" :style="'width:'+widthHead+';height:'+heightHead+';'">
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>

<script>
// 引入loading
import { Loading } from 'element-ui';
let loadingInstance = null
import Cookies from "js-cookie";

export default {
  name: "index",
  data() {
    return {
      baseFileUrl:process.env.VUE_APP_BASE_API+"接口地址",
      headers:{
        Authorization: Cookies.get('Admin-Token')
      },
    }
  },
  props: {
    widthHead:{
      default: '128px'
    },
    heightHead:{
      default: '128px'
    },
    value: {
      default: ''
    }
  },
  model: {
    prop: 'value',
    event: 'getValue'
  },
  methods:{

    // 上传校验
    beforeAvatarUpload (file) {
      // loading加载
      loadingInstance = Loading.service({ text: '努力加载中...'});
      // 校验图片大小 2就是2M
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
        // 上传失败,关闭loading
        loadingInstance.close();
      }
      return isLt2M;
    },
    // 上传成功
    handleAvatarSuccess (res, file) {
      if (res.code !== 200) {
        this.$message.error(res.message)
        return false
      }
      // 接口返回的图片传给父组件
      this.$emit('getValue', res.data)
      // 关闭loading加载
      loadingInstance.close();
      this.$message.success('上传成功')
    },
  }
}
</script>

<style lang="less" scoped>
/deep/ .el-upload {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}
.avatar {

  display: block;
}
</style>

注册组件

import UploadImage from "@/components/UploadImage"

export default {
  name: 'userList',
  components:{
    UploadImage
  },
  data(){
     return{}
  }
}

 使用

        vue代码

 <upload-image v-model="form.cover" @getValue="uploadCoverSuccess"></upload-image>

         js代码

    uploadCoverSuccess(file){
      this.form.cover = file.imgUrl
    },
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值