vue中使用elementUI组件的Upload 上传图片

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_39378691/article/details/83655052
1.安装elementUI:npm i element-ui -S
2.引入elementUI组件(main.js文件)
import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(Element, { size: 'small' })
3.访问Element官网【组件–Upload上传】

在这里插入图片描述

<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

在这里插入图片描述

5.script中的data( )和methods( )如下:
<script>
  export default {
    data() {
      return {
      	file:'',
        dialogImageUrl: '',
        dialogVisible: false,
        imgUrl:'',
        userId: '',
        uid:'',
        
        // 上传图片时附带的额外参数userId
        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){
		// console.log(res);
		if(res.status==200){
			this.imgUrl=res.data.imgUrl;
		}
	},
    }
  }
</script>
6.该组件的效果图如下:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_39378691/article/details/83655052