这里是把原生元素input作为上传文件,type=file,然后模拟点击该元素就可以实现上传。

<template>
  <div class="upload-button">
    <q-btn
      outline
      :color="buttonColor"
      :loading="uploading"
      :label="label"
      class="trigger-btn"
      @click="onClickButton"
    />
    <input
      type="file"
      ref="fileInput"
      style="display: none"
      @change="onFilesChanged"
    />
  </div>
</template>

<script lang="ts">
import Vue from 'vue'

export default Vue.extend({
  name: 'UploadButton',

  props: {
    label: {
      type: String,
      default: '上传'
    },
    accept: {
      type: String,
      default: ''
    },
    buttonColor: {
      type: String,
      default: 'primary'
    }
  },

  data () {
    return {
      uploading: false
    }
  },

  computed: {
  },

  methods: {
    onClickButton (_e: Event) {
      (this.$refs['fileInput'] as any).click()
    },

    onFilesChanged (e: Event) {
      let fileInput = this.$refs['fileInput'] as any
      let files = (e.target as any).files

      this.$emit('filesChanged', {
        files: files
      })

      if (files && files.length > 0) {
        fileInput.value = ''
      }
    }
  }
})
</script>

<style lang="stylus" scoped>
.upload-button {
  .trigger-btn {
    font-size: 13px;
    padding: 2px 8px;
    min-height: 1.58em;
  }
}
</style>

在这里插入图片描述

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐