1. 程式人生 > 實用技巧 >Vue小tips-d12

Vue小tips-d12

一、圖片上傳

1.el-upload元件

<el-upload
           action="#"
           list-type="picture-card"
           :auto-upload="false"
           :on-change="fileChange"
           >
    <i slot="default" class="el-icon-plus"></i>
    <div slot="file" slot-scope="{file}">
        <img 
class="el-upload-list__item-thumbnail" :src="file.url" alt=""> <span class="el-upload-list__item-actions"> <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)"> <i class="el-icon-zoom-in"></i> </
span> <span class="el-upload-list__item-delete"> <i class="el-icon-delete"></i> </span> </span> </div> </el-upload>

  • action 圖片上傳地址,#沒有上傳地址
  • list-type 檔案上傳按鈕的型別
  • auto-upload 是否自動上傳,false不自動上傳
  • on-change 選擇好檔案後觸發的函式

js程式碼

<script>
export default {
    data(){
        // 定義分類的初始資料
        return{
            dialogVisible:false,
            dialogImageUrl:''
            ...
        }
    }
    methods:{
        handlePictureCardPreview(){
            //圖片預覽的程式碼
        },
        fileChange(file){
            //檔案選擇後執行的業務邏輯程式碼
            this.info.img = file.raw;
        }
    }
}
</script>

2.資料提交

在js中,包含檔案型別的資料不能是物件格式,必須是表單才能夠提交檔案

  (1)生成一個空的表單

var data = new FormData()

  

  (2)把物件中的資料追加到表單中

//需要往表單中追加資料
for(let i in this.info){
    data.append(i,this.info[i]);
}

  

  (3)提交資料時提交的是表單資料

this.axios.post(url,data).then(res=>{
    if(res.data.code === 200){
        this.$router.push('/cate')
    }
})