基於elementUI實現圖片預覽元件
這是一個簡單的點選圖片預覽的元件
順便記錄一下寫元件期間踩的vue中scope的坑~
從註冊全域性元件開始叭!
- 專案目錄:
模仿elementUI目錄結構,目錄名是元件名,src中是元件原始檔(或者js服務檔案),檔案目錄下還有一個index.js用於同一管理src中的所有檔案,匯出並註冊,這個元件我們只有一個vue檔案件
- 先看index.js檔案裡有什麼:
//引入了src下的vue元件檔案 import starPicList from './src/star-pic-list'; /* istanbul ignore next */ starPicList.install = function(Vue) { //starPicList.name這就是後面可以使用的元件的名字(star-pic-list.vue檔案裡面定義的name),install是預設的一個方法 Vue.component(starPicList.name, starPicList); }; export default starPicList;
接下來介紹一下install方法:
Vue.use( plugin ):安裝 Vue.js 外掛。如果外掛是一個物件,必須提供 install 方法。如果外掛是一個函式,它會被作為 install 方法。install 方法將被作為 Vue 的引數呼叫。當 install 方法被同一個外掛多次呼叫,外掛將只會被安裝一次。Vue.js 的外掛應當有一個公開方法 install 。這個方法的第一個引數是 Vue 構造器,第二個引數是一個可選的選項物件:
- 匯出starPicList元件後在管理元件js檔案中引用,然後由這個統一管理js檔案匯出註冊到全域性即可:
好了,這些是廢話!
- 元件的使用:
<!--圖片列表形式,點選檢視圖片列表,點選顯示上(下)一張--> <template v-slot="scope"> <star-pic-list :data="scope.row.pic" :max-show="2"/> </template>
引數
data: 傳入圖片陣列;
max-show: 一次最多顯示幾張圖片
- 效果如下:
- 補充:vue元件開發中 style 新增scoped後,修改第三方元件樣式沒有效果問題:
在vue的開發中,我們通常和element-UI配合開發,就會遇到,在元件style中新增scoped後,element-ui中使用的子元件樣式無法改變。
不用scoped,去掉這個屬性,但是會汙染全域性樣式,(可配合less 或者 scss(推薦scss),所有樣式寫在當前元件id或class下面)
元件原始碼:
<template> <div id="star-pic-vue"> <template v-if="data"> <img v-for="item in images" :src="item" id="contract_url" @click="enlargePic"/> <template v-if="isDialogShow"> </template> <el-dialog :visible.sync="centerDialogVisible" modal close-on-click-modal custom-class="dialog" > <el-carousel :autoplay="false" arrow="always"> <el-carousel-item v-for="item in data" :key="item"> <img :src="item"> </el-carousel-item> </el-carousel> </el-dialog> </template> </div> </template> <script> export default { name: "star-pic-list", props: ["data","maxShow"], data(){ return{ centerDialogVisible: false, showPic: '', isDialogShow: false, index: 0, } }, computed: { images() { if (this.data instanceof Array && this.data.length > 2) { return this.data.splice(0,this.maxShow) } else { return this.data } } }, methods: { // 放大圖片 enlargePic(e){ this.isDialogShow = true; this.centerDialogVisible = true; this.showPic = this.data[0]; console.log(this.images) }, } } </script> <style lang="less"> #star-pic-vue{ width: 200px; height: auto; display: flex; flex-wrap: wrap; img{ width: 80px; height: 80px; margin: 4px; } .dialog { img{ width: 100%; height: 100%; margin: 0; } } .el-carousel__item h3 { color: #475669; font-size: 18px; opacity: 0.75; line-height: 300px; margin: 0; height: 100%; width: 100%; } .el-dialog__header{ display: none; } .el-dialog__body { padding: 0 !important; margin: 0 !important; height: 600px; } .el-carousel{ height: 100%; } .el-carousel__container { height: 100%; } } </style>
更多元件點選這兒 --> link : github>components>star-pic-list