vue3中element+上传文件与vue-cropper裁剪插件配合上传图片

591 阅读1分钟
官网DEEMO地址 github.xyxiao.cn/vue-cropper…

官网 github.com/xyxiao001/v…

最近需要做一个上传封面的功能,网上冲浪一通,选择vue-cropper这个插件觉得很合适,记录一下

效果样式如图

image.png

image.png

div class="cut">
      <el-upload
        v-if="cutFlage"
        action="#"
        class="post-uploader"
        :auto-upload="false"
        :show-file-list="false"
        accept=".png,.jpg,.gif"
        :on-change="postChange"
      >
        <el-icon><Plus /></el-icon>
        <div class="el-upload__text">
          上传封面<br />
          <span
            >建议尺寸为612*440,只支持JPG/PNG/GIF,GIF文件不能动画化,大小不超过5M</span
          >
        </div>
      </el-upload>
      <div class="cut" v-else>
        <VueCropper
          ref="cropper"
          :img="option.img"
          :output-size="option.size"
          :output-type="option.outputType"
          :info="true"
          :full="option.full"
          :fixed="option.fixed"
          :can-move="option.canMove"
          :can-move-box="option.canMoveBox"
          :fixed-box="option.fixedBox"
          :original="option.original"
          :auto-crop="option.autoCrop"
          :auto-crop-width="option.autoCropWidth"
          :auto-crop-height="option.autoCropHeight"
          :center-box="option.centerBox"
          @realTime="realTime"
        ></VueCropper>
      </div>
    </div>
引入vue-cropper并初始化
import { reactive } from 'vue'
import 'vue-cropper/dist/index.css'
import { VueCropper } from 'vue-cropper'

export default {
  components: {  VueCropper },
  data() {
    return 
      cutFlage: true
    }
  },
  setup() {
  // 初始化,参数设定,相信参考官网
    const option = reactive({
      size: 1,
      full: false,
      outputType: 'png',
      canMove: true,
      fixed: false,
      fixedBox: false,
      original: false,
      canMoveBox: true,
      autoCrop: true,
      // 只有自动截图开启 宽度高度才生效
      autoCropWidth: 612,
      autoCropHeight: 440,
      centerBox: false,
      high: true,
      max: 99999
    })
    return { option }
  },
  methods: {
    // 文件上传
    postChange(val) {
      // 记录文件名
      this.fileName = val.name
      var reader = new FileReader()
      reader.readAsDataURL(val.raw)
      reader.onload = () => {
        this.option.img = reader.result
      }
      console.log(this.option)
      this.cutFlage = false
    },
    // 裁切事件可以获取到裁切后的图片
    realTime(data) 
      // 获取base64编码
      this.$refs.cropper.getCropData((val) => 
        // 获取到的值给img可以实现小图实时预览
      })
    }
  }
}

样式,简单示例


  .cut {
    width: 300px;
    height: 300px;
    text-align: center;
    border: 1px solid #ccc;
  }