This is the fourth day of my participation in the More text Challenge. For details, see more text Challenge

Some time ago, when I was developing a project, I had a business requirement to upload pictures. When I was doing mobile terminal development, uploading pictures was also a very basic requirement. However, for front-end development, we need to study how to achieve it. Our project uses Vant components, and then I go directly to the official website of Vant components to check how to use the uploaded files, and then I can directly use the API tutorial on the official website. If I have any questions, I can also ask Baidu or my friends.

Without further ado, let’s share the specific method of uploading pictures. The specific steps are as follows.

1, the introduction of

To introduce the Uploader component into your project, open the project, find the main.js file, and copy the following code into it:

        import Vue from 'vue';
	import { Uploader } from 'vant';
	Vue.use(Uploader);
Copy the code

2, the use of specific document writing method

My example directly upload the picture module with a component to encapsulate, so convenient to call and management, the specific component file written as follows:

<template> <div class="file-uploader"> <div class="credential-infor"> <van-uploader :after-read="afterRead" Class ="img-uploader" :max-count="1" </div> </div> </template> <script> export default {name: "FileUploader", data() { return { fileList: [], imgKey:[] }; }, created() {}, computed: {}, methods: {afterRead(file) {// Upload the file to the server. Let imgFile = new FormData(); imgFile.append("fileType", 'IMAGE'); imgFile.append("file", this.fileList[0].file); this.$service.apply .uploadImage({ data: imgFile, }) .then((r) => { if (r.data.success) { this.imgKey.push(r.data.data.key) } }); }}}; </script> <style lang="scss"> .file-uploader { .credential-infor { margin: px2em(20); height: px2em(100); } } </style>Copy the code

To explain how to use the above code, first introduce the image upload component into the HTML:

<van-uploader :after-read="afterRead" />

Then do the following in js:

Export default {methods: {afterRead(file) {afterRead(file) {// Upload the file to the server. ,}}};Copy the code

In fact, you can also add a preview effect after uploading the image. The code above is not written, but I will add it as follows: bind the data source of the image to the component, as shown below:

<van-uploader :after-read="afterRead" v-model="fileList" multiple />Copy the code

Use v-Model to bind a list of uploaded images and show a preview of the list of images.

That is all the content of this chapter. Welcome to pay attention to the wechat public number “Program ape by Three managers” and the Sina Weibo of three managers “Three managers 666”. Welcome to pay attention!