vue实现头像预览功能

一个小记录。
下面的html是使用了element-ui实现具体样式,但是选取图片文件需要用原生的input框。原生的样式很难修改,就可以将原生的input框隐藏起来,用elbutton触发原生的input框的click事件。

<el-form-item label="头像预览">
  <!-- 显示初始的图片 -->
  <img src="@/assets/cover.jpg" alt="" class="cover-img" ref="imgRef" />
  <br />
  <!-- 文件选择框,默认被隐藏 -->
  <input type="file" style="display: none;" accept="image/*" ref="iptFileRef" @change="changeCover"/>
  <!-- 选择封面的按钮 -->
  <el-button type="text"  @click="selCover">+ 选择封面</el-button>
</el-form-item>
    selCover(){
        this.$refs.iptFileRef.click()
    },
    changeCover(e){
        // console.log(e.target.files[0])
        const files=e.target.files
        if(files.length===0){
            this.pubForm.cover_img=null
        }else{
            this.pubForm.cover_img=files[0]
        }
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue.js 实现头像预览功能可以结合使用`vue-image-preview`组件和`vue-cropperjs`组件来实现。`vue-image-preview`用于预览头像,`vue-cropperjs`用于剪裁头像。 下面是一个基本的使用示例: 1. 安装`vue-image-preview`和`vue-cropperjs`组件: ``` npm install vue-image-preview vue-cropperjs --save ``` 2. 在Vue.js应用程序的入口文件中引入`vue-image-preview`和`vue-cropperjs`组件: ```javascript import Vue from 'vue' import VueImagePreview from 'vue-image-preview' import VueCropper from 'vue-cropperjs' import 'vue-image-preview/dist/vue-image-preview.css' import 'cropperjs/dist/cropper.css' Vue.use(VueImagePreview) Vue.component('VueCropper', VueCropper) ``` 3. 在需要预览和剪裁头像的组件中使用`vue-image-preview`和`vue-cropperjs`组件: ```vue <template> <div> <img :src="imageUrl" @click="showPreview"> <vue-cropper :img="imageUrl" ref="cropper" :guides="true"></vue-cropper> </div> </template> <script> import VueCropper from 'vue-cropperjs' export default { data() { return { imageUrl: 'https://example.com/avatar.jpg' } }, methods: { showPreview() { this.$preview.show({ images: [{ src: this.imageUrl }] }) }, cropAvatar() { const canvas = this.$refs.cropper.getCroppedCanvas() const croppedImage = canvas.toDataURL('image/jpeg') // 将剪裁后的头像上传到服务器 } }, components: { VueCropper } } </script> ``` 在这个示例中,我们在点击头像时调用了`showPreview()`方法,该方法使用了`vue-image-preview`组件的预览功能,并传入了需要预览头像路径。同时,我们还在组件中使用了`vue-cropperjs`组件,在预览头像时可以对头像进行剪裁操作,剪裁后的头像可以通过`toDataURL()`方法获取到。 需要注意的是,在使用`vue-cropperjs`组件时,需要在组件中添加`ref`属性,以便在剪裁头像时获取到组件的实例。同时,在剪裁头像后,可以将剪裁后的头像上传到服务器。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值