返回

用Vue的多元化方法实现图片上传

前端

引子
只谈技术不谈业务都是耍流氓,为了让内容更加贴合实战,我们首先来设定一个需要实现的业务场景。假设我们要做一个后台系统添加商品的页面,有一些商品名称、信息等字段,还有需要上传商品轮播图的需求。本文将以Vue、Element-ui和组件封装为基础,探索如何实现图片上传功能。

事前准备
在开始编码之前,我们需要先准备一些东西。

  1. 安装必要的依赖:Vue.js、Element-ui、axios。
  2. 搭建一个基本的Vue项目。
  3. 在Element-ui的官方文档中找到上传组件的用法。

组件封装
为了实现上传功能,我们将把上传组件封装成一个独立的组件,以便在其他地方复用。
首先,在src目录下创建一个components文件夹,并在其中创建一个名为upload.vue的文件。

<template>
  <el-upload
    :action="action"
    :headers="headers"
    :multiple="multiple"
    :data="data"
    :name="name"
    :withCredentials="withCredentials"
    :show-file-list="showFileList"
    :on-change="handleChange"
    :on-success="handleSuccess"
    :on-error="handleError"
  >
    <el-button slot="trigger" type="primary">选择文件</el-button>
  </el-upload>
</template>

<script>
export default {
  props: {
    action: {
      type: String,
      required: true
    },
    headers: {
      type: Object,
      default: () => {}
    },
    multiple: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => {}
    },
    name: {
      type: String,
      default: 'file'
    },
    withCredentials: {
      type: Boolean,
      default: false
    },
    showFileList: {
      type: Boolean,
      default: true
    }
  },
  methods: {
    handleChange(file, fileList) {
      this.$emit('change', file, fileList);
    },
    handleSuccess(response, file, fileList) {
      this.$emit('success', response, file, fileList);
    },
    handleError(err, file, fileList) {
      this.$emit('error', err, file, fileList);
    }
  }
};
</script>

在main.js中,注册上传组件。

import Upload from '@/components/upload';

Vue.component('Upload', Upload);

这样,我们就可以在任何地方使用这个上传组件了。

实战应用
在商品添加页面的模板中,使用上传组件。

<template>
  <div>
    <Upload action="/api/upload" @change="handleChange" @success="handleSuccess" @error="handleError"></Upload>
  </div>
</template>

<script>
export default {
  methods: {
    handleChange(file, fileList) {
      console.log(file, fileList);
    },
    handleSuccess(response, file, fileList) {
      console.log(response, file, fileList);
    },
    handleError(err, file, fileList) {
      console.log(err, file, fileList);
    }
  }
};
</script>

在商品添加页面的脚本中,处理上传组件的事件。

import Upload from '@/components/upload';

export default {
  components: { Upload },
  methods: {
    handleChange(file, fileList) {
      console.log(file, fileList);
    },
    handleSuccess(response, file, fileList) {
      console.log(response, file, fileList);
    },
    handleError(err, file, fileList) {
      console.log(err, file, fileList);
    }
  }
};

总结
通过上述步骤,我们已经成功地用Vue实现了图片上传功能。在实际项目中,我们还可以根据需要对上传组件进行更多的封装,例如增加文件类型、大小和数量的限制,以及实时上传进度条等功能。这些功能的实现方法有很多种,大家可以根据自己的实际情况进行选择。