1. 安装elementUI:npm i element-ui -S
2. 在main.js中引入elementUI
import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(Element, { size: 'small' })
3. 访问Element官网【组件–Upload上传】
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e2c602be5e71df03bede0433e533b36f.png#pic_center)
<el-upload
action="https://jsonplaceholder.typicode.com/posts/"
list-type="picture-card"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove">
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt="">
</el-dialog>
<script>
export default {
data() {
return {
dialogImageUrl: '',
dialogVisible: false
};
},
methods: {
handleRemove(file, fileList) {
console.log(file, fileList);
},
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
}
}
}
</script>
4. 我的需求:点击保存按钮手动上传,只能上传一张图片,参数为userId
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/fd595eca60235410d7248df2e252db23.png#pic_center)
5. script中的data( )和methods( )如下:
export default {
data() {
return {
file:'',
dialogImageUrl: '',
dialogVisible: false,
imgUrl:'',
userId: '',
uid:'',
resData:{
userId: window.localStorage["userId"]
},
};
},
methods: {
handleRemove(file, fileList) {
console.log(file, fileList);
},
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
},
submit2:function(res){
this.$refs.upload.submit();
},
onSuccess:function(res){
if(res.status==200){
this.imgUrl=res.data.imgUrl;
}
},
}
}
6. 该组件的效果图如下:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6b15c923628b7af1a8be0cdfb75276ba.png#pic_center)