1.上传图片组件
子组件代码
//html代码
<template>
<el-dialog title="产品图片" :visible.sync="dialogPicVisible" width="30%">
<el-form
:model="PicForm"
:rules="rules"
ref="PicForm"
label-width="100px"
class="demo-PicForm"
lock-scroll="true"
>
<el-form-item label="产品图片" prop="picture" class="pic picture">
<el-upload
required
class="avatar-uploader"
:action="imgurl()" //上传接口
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
:headers="headers" //必须带token表头
>
<img v-if="imageUrl" :src="imageUrl" class="avatar" />
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<span id="picBtn">请选择图片</span>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="onSubmit()" class="dialogBtn">提交</el-button>
</div>
</el-dialog>
</template>
<script>
//js代码
import {getToken} from "@/utils/auth"; //获取token
import axios from 'axios';
export default {
name: "index",
computed: {
headers() {
return {
"access-token": this.token // 直接从本地获取token就行
};
},
},
data() {
return {
token: getToken(),
imagesUrl:"",
PicForm: {
picture: "",
id: 0}
}
},
methods: {
openModal() {
if (this.$refs.PicForm) {
this.$refs.PicForm.resetFields();
}
this.dialogPicVisible = true;
},
imgurl() {
//上传图片的接口
return axios.defaults.baseURL + "接口";
},
//上传成功方法
handleAvatarSuccess(res, file) {
this.imageUrl = URL.createObjectURL(file.raw);
// console.log(res.data, "图片路径");
this.PicForm.picture = res.data; //最新上传成功的图片路径
},
//图片大小限制方法
beforeAvatarUpload(file) {
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
this.$message.error("上传头像图片大小不能超过 2MB!");
}
return isLt2M;
},
onSubmit() {
this.$axios.put("接口", this.PicForm).then(res => {
if (res.data.code == 0) {
this.$message.success("上传成功");
this.dialogPicVisible = false;
this.reload(); //刷新方法
}
});
}
}
}
</script>
父组件代码
//html代码
<el-button @click="getPic()"">产品图片</el-button>
<Updataimg ref="updataimg"></Updataimg> //使用
//js代码
import Updataimg from "./updataimg"; //引入
components: { Updataimg },
// 图片
getPic() {
this.$refs.updataimg.openModal();
},