Vant2.x 是一个轻量、可靠的移动端组件库,于 2017 年开源。

一、全局安装vant

npm i vant -S


二、安装babel插件,配置按需引入

npm i babel-plugin-import -D

// babel.config.js

module.exports = {
  presets: [
    '@vue/cli-plugin-babel/preset'
  ],
  plugins: [
    ['import', {
      libraryName: 'vant',
      libraryDirectory: 'es',
      style: true
    }, 'vant']
  ]
}


三、upload-image.vue

<template>
  <van-uploader
    :file-list="uploadFileList"
    :accept="acceptType"
    :max-count="maxCounts"
    :max-size="uploadSize"
    :upload-text="uploadText"
    :after-read="readFileHandle"
    @delete="delFileHandle"
    @oversize="onOversizeToast"
  />
</template>

<script>
import { Uploader } from 'vant'

export default {
  name: 'UploadImageList',
  components: {
    [Uploader.name]: Uploader
  },
  props: {
    /***
     * uploadFileList格式
     * [{name: '', url: '', isImage: true}]
     */
    uploadFileList: {
      type: Array,
      required: true,
      default: () => []
    },
    uploadText: {
      type: String,
      default: '上传图片'
    },
    maxCounts: {
      type: Number,
      default: 99
    },
    acceptType: {
      type: String,
      default: 'image/jpeg,image/jpg,image/png'
    },
    uploadSize: {
      type: Number,
      default: 5242880 // 5m
    }
  },
  methods: {
    readFileHandle (file) {
      this.$emit('readFileEvents', file)
    },

    delFileHandle (file, detail) {
      this.$emit('delEvents', file, detail)
    },

    onOversizeToast () {
      this.$toast('文件大小不能超过5M')
      return false
    }
  }
}
</script>


四、引用页面

<template>
  <div class="notice-detail-page">
    <image-upload-list
      :max-counts="1"
      :upload-file-list="uploadList"
      @delEvents="onDelFileHandle"
      @readFileEvents="onReadFileHandle"
    />
  </div>
</template>

<script>
import ImageUploadList from './upload-image.vue'

export default {
  name: 'noticeDetail',
  components: { ImageUploadList },
  data () {
    return {
      uploadList: []
    }
  },
  methods: {
    onReadFileHandle (files) {
      console.log(files)
      this.uploadList.push({
        isImage: true,
        url: files.content,
        name: files.file.name
      })
    },

    onDelFileHandle (file, item) {
      console.log(file, item)
      const { index } = item
      this.uploadList.splice(index, 1)
    }
  }
}
</script>