vue中使用elementUI元件的Upload 上傳圖片
阿新 • • 發佈:2018-11-19
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>