隨着互聯網時代的到來,圖片成為了人們生活中重要的一部分。在網站和應用程序中,圖片預覽功能更是必不可少。在Vue.js框架中,ElementUI是一個比較成熟的組件庫,其中包含了豐富的組件和工具,也包括圖片預覽功能。本文將詳細介紹如何在Vue.js中使用ElementUI來實現圖片預覽。
一、安裝ElementUI
首先,我們需要將ElementUI添加到我們的項目中。我們可以使用npm命令來安裝它。
npm i element-ui -S
如果你使用的是VueCLI 3.x來創建項目,你可以使用VueCLI提供的插件快速安裝ElementUI:
vue add element
這一步完成後,我們需要在Vue項目的入口文件main.js中引入和使用ElementUI。
// 引入ElementUI的CSS和JS文件
import 'element-ui/lib/theme-chalk/index.css';
import ElementUI from 'element-ui';
Vue.use(ElementUI);
二、使用el-upload組件
要實現圖片預覽的功能,我們需要使用ElementUI的el-upload組件。el-upload組件是一個上傳文件的組件,可以讓用戶將本地的文件上傳到服務器。在本例中,我們需要使用el-upload的文件列表顯示和文件預覽功能。
首先,我們需要在Vue文件中定義一個data屬性,用於保存上傳的文件列表:
data() {
return {
fileList: []
}
}
接下來,在Vue模板中添加el-upload組件,並設置相關屬性:
<el-upload
class="upload-demo"
action="//jsonplaceholder.typicode.com/posts/"
:file-list="fileList"
multiple
:auto-upload="false"
list-type="picture"
:on-preview="handlePicturePreview"
:on-remove="handleRemove"
>
<el-button slot="trigger" size="small" type="primary">選取文件</el-button>
<el-button size="small" type="success" @click="submitUpload">上傳到服務器</el-button>
<span slot="tip" class="upload-tip">只能上傳jpg/png文件,且不超過500kb</span>
</el-upload>
在上述代碼中,我們設置了el-upload的一些屬性,如action設置為“//jsonplaceholder.typicode.com/posts/”(假的接口地址),file-list保存上傳的文件列表,multiple表示可以上傳多個文件,auto-upload設置為false表示不自動上傳文件,list-type設置為“picture”表示文件列表的顯示形式為圖片,on-preview事件處理函數設置為handlePicturePreview,on-remove事件處理函數設置為handleRemove。
接下來,我們需要為handlePicturePreview和handleRemove事件處理函數添加代碼:
methods: {
handlePicturePreview(file) {
this.$preview(file.url, '預覽');
},
handleRemove(file, fileList) {
console.log(file, fileList);
}
}
在handlePicturePreview事件處理函數中,我們調用了Vue.prototype.$preview方法,這個方法是ElementUI提供的一個用於預覽圖片的方法。該方法有兩個參數,第一個參數為圖片URL,第二個參數為彈出窗口的標題。
在handleRemove事件處理函數中,我們可以在控制台中看到上傳的文件信息。
三、完整代碼示例
下面是完整的Vue單文件組件的代碼示例:
<template>
<el-upload
class="upload-demo"
action="//jsonplaceholder.typicode.com/posts/"
:file-list="fileList"
multiple
:auto-upload="false"
list-type="picture"
:on-preview="handlePicturePreview"
:on-remove="handleRemove"
>
<el-button slot="trigger" size="small" type="primary">選取文件</el-button>
<el-button size="small" type="success" @click="submitUpload">上傳到服務器</el-button>
<span slot="tip" class="upload-tip">只能上傳jpg/png文件,且不超過500kb</span>
</el-upload>
</template>
<script>
export default {
data() {
return {
fileList: []
}
},
methods: {
handlePicturePreview(file) {
this.$preview(file.url, '預覽');
},
handleRemove(file, fileList) {
console.log(file, fileList);
}
}
}
</script>
通過這個簡單的例子,我們可以看到ElementUI提供了非常簡單易用的el-upload組件,在Vue.js中實現圖片預覽功能十分方便。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/288738.html