VUE + Element UI 上传组件

vue修改配置文件(vue.config.js) 有时候会出现没有重启,得手动重启javascript

module.exports = {
    //baseUrl 从 Vue CLI 3.3 起已弃用,请使用publicPath
    baseUrl: './',
    // outputDir: 在npm run build 或 yarn build 时 ,生成文件的目录名称(要和baseUrl的生产环境路径一致)
    outputDir: "mycli3",
    //用于放置生成的静态资源 (js、css、img、fonts) 的;(项目打包以后,静态资源会放在这个文件夹下)
    assetsDir: 'static',
    productionSourceMap: false,
    devServer: {
//启动本地端口
        port: 3666,
//开启多个代理
        proxy: {
//url路径中包含 /admin 会跳转到target
            '/admin': {
                target: 'http://localhost:8666',
//开启代理:在本地会建立一个虚拟服务端,而后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
                changeOrigin: true,
//将url中/admin 部分替换为空
                pathRewrite: {
                    '^/admin':''
                }
            }
        }
    }
}

前端代码,  el-upload action参数必须是String(能够接受一个函数,返回String),vue.config.js proxy配置了/admin会走代理跳target。url写错了,会一直跳转失败,有些经常使用的单词,data,methods,components ,写错了会出现调用失败,全部都检查了,还没解决能够看看这里css

action实现不了 ,那就重写action,用http-request,这里须要注意html

1,上传须要 建立const fileForm = new FormData(); 对象,再存值前端

2,调用后端接口,须要设置 headers: { "content-type": "multipart/form-data" }vue

<el-form-item label="图标:">
 <el-upload
 //可接受的文件格式
   accept="image/*"
 //是否展现文件列表
   :show-file-list="false"
   class="avatar-uploader"
 //必填,文件上传路径,String,可接受函数,里面返回url
   action="/admin/util/updload"
 //重写action,本身实现上传逻辑,action部分能够为空
   :http-request="handleUpload"
 //上传成功回调
   :on-success="handleUploadSuccess">
  <img v-if="form.image" :src="form.image" class="avatar" />
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
 </el-upload>
</el-form-item>   

<script>
//省略代码…………
//上传函数,http-request 能够接受一个参数
handleUpload(param){
   console.info("开始上传", param.file)
   const fileForm = new FormData();
   fileForm.append("file", param.file);
   actions.uploadImage(fileForm).then(res =>{
       this.$set(this.form, "image", res.data.data)
   })
},
…………

//封装的函数部分(这里是一个独立的文件)
uploadImage(params) {
    // 根据后台需求的数据格式肯定headers
    return axios.post('/admin/util/upload', params, {
            headers: { "content-type": "multipart/form-data" }
    })
},
</script>  


<style lang="less" scoped>
//图片上传样式
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
  }
.avatar-uploader /deep/ .el-upload {
    width: 178px;
  }
  .avatar-uploader /deep/ .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

 

vue.config.js 配置文件 详解  https://www.cnblogs.com/yanl55555/p/11792583.htmljava

相关文章
相关标签/搜索