返回

使用 Vue-cli+Element+vue-cropper 实现头像裁剪

前端

简介

在现代网络应用程序中,头像是一个重要的元素,它可以帮助用户识别彼此并建立个人联系。头像通常是用户上传的图片,但有时需要对图片进行裁剪以使其适合应用程序的布局或设计。

使用 Vue-cli+Element+vue-cropper 实现头像裁剪

安装 Vue.js、Element UI 和 vue-cropper

首先,我们需要安装 Vue.js、Element UI 和 vue-cropper。我们可以使用 npm 来安装这些库:

npm install vue vue-router element-ui vue-cropper

创建 Vue.js 项目

安装完成后,我们可以创建一个新的 Vue.js 项目:

vue create my-app

添加 Element UI 和 vue-cropper

接下来,我们需要将 Element UI 和 vue-cropper 添加到我们的项目中。我们可以使用以下命令来做到这一点:

npm install element-ui --save
npm install vue-cropper --save

配置 Vue.js 项目

在我们的项目根目录下的 main.js 文件中,我们需要配置 Vue.js 和 Element UI:

import Vue from 'vue'
import App from './App.vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

Vue.use(ElementUI)

new Vue({
  render: h => h(App),
}).$mount('#app')

创建头像裁剪组件

现在,我们可以创建一个头像裁剪组件。我们可以创建一个新的文件 Cropper.vue,并在其中添加以下代码:

<template>
  <el-upload
    class="avatar-uploader"
    :action="uploadUrl"
    :show-file-list="false"
    :on-success="handleSuccess"
    :before-upload="beforeUpload">
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>

<script>
import Vue from 'vue'
import Cropper from 'vue-cropper'

export default {
  name: 'Cropper',
  components: { Cropper },
  data() {
    return {
      imageUrl: '',
      uploadUrl: '/upload'
    }
  },
  methods: {
    handleSuccess(response) {
      this.imageUrl = response.data.url
    },
    beforeUpload(file) {
      this.cropper.imgRef.src = URL.createObjectURL(file)
    }
  },
  mounted() {
    this.cropper = new Cropper(this.$refs.cropper, {
      aspectRatio: 1,
      viewMode: 1,
      preview: '.avatar-preview'
    })
  }
}
</script>

<style>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.avatar {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
</style>

使用头像裁剪组件

现在,我们可以使用头像裁剪组件了。我们可以