Croppa 裁剪头像,上传到oss,再提交给后台接口(ajax请求,保存赋值给全局变量没有用的解决方案)

插件网址

https://zhanziyang.github.io/vue-croppa/#/demos

第一步:npm

npm install --save vue-croppa

第二步:main.js引入

import 'vue-croppa/dist/vue-croppa.css'
import Vue from 'vue'
 import Croppa from 'vue-croppa'
 Vue.use(Croppa)       

第三步:html页面代码

  <croppa v-model="croppa" :show-remove-button="true" :width="160" :height="160" :prevent-white-space="true" initial-size="natural"></croppa>
   <Button style="width: 100px" type="primary" size="large" long :loading="sourloading" @click="upload">提交</Button>
   
// 这个插件里面有许多属性
几个常用的:
show-remove-button="true"   是否显示右上角的 × 叉叉
prevent-white-space="true"  禁止有白框的出现  //具体效果自己试一下
disabled=true    禁止选择
initial-size="natural"   初始尺寸

https://www.npmjs.com/package/vue-croppa // 具体属性值有哪些可以自己去看一下

第四步:js 部分

创建一个变量
data(){
          return{
			 croppa: {},
			 fileimgid :'',
			 }
			 }

 methods:{
        //图片裁剪
          upload(){
            if (!this.croppa.hasImage()) {
              alert('暂无图片')
              return
            }
            this.croppa.generateBlob((blob) => {
            
              var fd = new FormData()
              // !!!!!!!重点说明,这里,必须要保存一个指向,要不然success 里面的this不是指向全局的,全局变量保存
              也就没有用,
              //!!!!!!!!!!!!!!!!!!!!!!!!!
              var that  = this
              
              fd.append('file', blob, 'filename.jpg')
              fd.append('other', 'blahblahblah')
              $.ajax({
                url: this.uploadAction,    // 这里是你上传到oss 或者其他服务器的地址,我直接把地址赋值给全局变量
                data: fd,
                async:false,  // 这里也必须异步请求!!!
                type: 'POST',
                processData: false,
                contentType: false,
                success: function (data) {
                  if(data.errcode == 2000){
                    that.fileimgid  = data.result
                    // 调用第二个接口
                    that.Editall()
                  }
                }
              })
            })
        },
          Editall(){
       
            console.log(this.fileimgid)
            // 下面是提交的请求  这里是第二个请求,可以自己写了,写太多反而更乱
            
                 }

ajax请求,保存赋值给全局变量没有用的解决方案

怕有的人不看代码,在这里再写一下
1、 async:false, // 异步
2、保存this的指向(写在请求之前)
var that = this

如有疑问或者本文有什么出错的地方,欢迎评论

发布了26 篇原创文章 · 获赞 29 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44143512/article/details/97010860