Vue封装一个类似输入框的上传文件组件,可以直接使用

实现的效果类似下面的样子:

当用户没有选择任何文件的时候,输入框里面有默认的站位浅色字体,输入框的边框颜色也是浅色的,当用户鼠标放上去后,边框颜色加深,当用户选中一个文件之后,默认站位字体消失,变为文件名称,并且字体颜色变为深色模式。

没有选择任何文件时候的样式:

我使用的是一个div盒子包裹了一个span标签实现的类似伪输入框效果,所以下面直接上代码:这个组件我使用一个弹窗包裹起来了,你们按自己的需求可以去掉:

<template>
  <el-dialog
    :visible.sync="licenseImp"
    :before-close="handleClose"
    title="导入License"
    top="20vh"
    width="40%"
  >
    <div class="license-box">
      <div class="license-input" @click="openFiles">
        <span
          :class="{
            place: fileName === '请选择文件',
            file: fileName !== '请选择文件'
          }"
        >{
   
   { fileName }}</span
        >
      </div>
      <el-button
        size="small"
        icon="el-icon-upload"
      >上传文件</el-button
      >
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="licenseImp = false">取 消</el-button>
      <el-button
        size="small"
        type="primary"
        @click="licenseImp = false"
      >确 定</el-button
      >
    </span>
    <input
      id="open"
      type="file"
      name="filename"
      style="display: none"
      @change="changeFile"
    >
  </el-dialog>
</template>

<script>
export default {
  name: 'LicenseImp',
  data() {
    return {
      licenseImp: true,
      fileName: '请选择文件'
    }
  },
  methods: {
    handleClose(done) {
      this.$confirm('确认关闭?')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    openFiles() {
      console.log('打开文件对话框')
      document.getElementById('open').click()
      // const fileType = ['xls', 'xlsx', 'et']
      // const inputFile = document.createElement('input')
      // inputFile.type = 'file'
      // inputFile.style.display = 'none'
      // document.body.appendChild(inputFile)
      // inputFile.click()
      // inputFile.addEventListener('change', function() {
      //   const file = inputFile.files[0]
      //   console.log('file-----', file)
      // })
    },
    changeFile() {
      const fu = document.getElementById('open')
      if (fu === null || !fu.files[0]) return
      console.log('fu---', fu.files[0].name)
      this.fileName = fu.files[0].name
      this.fileSize = fu.files[0].size
      var form = {}
      form = new FormData()
      form.append('file', fu.files[0])
      // 调用上传接口上传吧
      console.log('form---', form)
    }
  }
}
</script>

<style lang="scss" scoped>
.license-box {
  display: flex;
  justify-content: center;
  .license-input {
    width: 320px;
    height: 33px;
    border: 1px solid #aeaeaf;
    line-height: 33px;
    border-radius: 3px;
    padding: 0 5px 0 8px;
    margin-right: 15px;
    cursor: pointer;
    .place {
      color: rgb(159, 158, 158);
    }
    .file{
      color: #222;
    }
  }

  .license-input:hover{
    border: 1px solid rgb(55, 52, 52);
  }
}
</style>

猜你喜欢

转载自blog.csdn.net/weixin_44786530/article/details/130987572