vue使用組件實現圖片上傳


  文件上傳的話可以使用element組件,也可以使用第三方組件,我這里使用的是ImageCropper和PanThumb

  首先下載兩個文件夾:鏈接:https://pan.baidu.com/s/1BsE0VjoTj2p1jRpzvgkFvg   提取碼:628i ,然后把這個兩個文件夾丟到vue的component目錄下,使用之后是這個樣子的,感覺還行:

 

  vue的tamplate代碼:

<template>
  <div class=''>
    <el-form label-width="120px">
      <!-- 頭像 -->
      <el-form-item label="頭像">
        <!-- 頭銜縮略圖 -->
        <pan-thumb :image="teacher.avatar" />
        <!-- 文件上傳按鈕 -->
        <el-button type="primary"
                   icon="el-icon-upload"
                   @click="imagecropperShow=true">更換頭像
        </el-button>
        <!-- imagecropperKey每次都要加一,不然在第一次修改成功之后,后續的要修改這個頭像
        的話,只會顯示上傳成功,而不是可以繼續上傳 -->
        <image-cropper v-show="imagecropperShow"
                       :width="300"
                       :height="300"
                       :key="imagecropperKey"
                       :url="uploadOSSUrl"
                       field="file"
                       @close="close"
                       @crop-upload-success="cropSuccess" />
      </el-form-item>
      <el-form-item>
        <el-button :disabled="saveBtnDisabled"
                   type="primary"
                   @click="saveOrUpdate">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

 

  script部分代碼:
import ImageCropper from '@/components/ImageCropper'
import PanThumb from '@/components/PanThumb'
export default {
  // import引入的組件需要注入到對象中才能使用
  components: { ImageCropper, PanThumb },
  data () {
    // 這里存放數據
    return {
      teacher: {
        name: '',
        avatar: ''
      },
      saveBtnDisabled: false, // 保存按鈕是否禁用
      imagecropperShow: false, // 上傳彈框組件是否顯示
      imagecropperKey: 0, //上傳組件key值
      uploadOSSUrl: process.env.BASE_API + '/eduoss/fileOss'//獲取后台上傳OSS的url,這里的BASE_API自己改成后端調用的地址
    }
  },
     // 方法集合
  methods: {
    //關閉上傳頭像彈框
    close () {
      this.imagecropperShow = false
      //關閉時讓組件初始化
      this.imagecropperKey = this.imagecropperKey + 1
    },
    //上傳成功方法,這里會獲取OSS中圖片的url
    cropSuccess (data) {
      this.imagecropperShow = false
      this.teacher.avatar = data.url
      //上傳時讓組件初始化
      this.imagecropperKey = this.imagecropperKey + 1
    },
//添加和保存,根據是否有id判斷是新增還是修改
    saveOrUpdate () {
      //這里就是調用axios保存teacher對象中的數據,自己定義
    }  
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM