首页
归档
笔记
树洞
搜索
友言

文章详情

Interesting People Record Interesting.

/ JavaScript / 文章详情

基于element ui的图片预览插件

Sonder
2020-11-24
2053字
5分钟
浏览 (3.2k)

写插件很简单,满足两个条件即可,一、基本的逻辑思路,二、熟悉插件语法要求。本次Vue插件也比较简单,点击“查看图片”用轮播的方式限制用户上传的图片,如图:
image.png
image.png

项目采用的是vue-element-admin

src/components下新建imgPreview文件夹,然后在该文件夹下新建ImgPreview.vueindex.js两个文件,代码如下:

ImgPreivew.vue

复制代码
<template>
 <el-dialog
   :visible.sync="isShowImageDialog"
   @closed="clearImg"
 >
   <el-carousel indicator-position="outside" height="600px">
     <el-carousel-item v-for="src in imgs">
       <img :src="src" style="max-width: 100%;max-height: 100%;display: block; margin: 0 auto;"/>
     </el-carousel-item>
   </el-carousel>
 </el-dialog>
</template>

<script>
export default {
 name: 'ImgPreview',
 data() {
   return {
     imgs: '',
     isShowImageDialog: false
   }
 },
 methods: {
   clearImg() {
     this.imgs = null
   }
 }
}
</script>

<style scoped>

</style>

index.js

复制代码
import ImgPreviewComponent from './ImgPreview'

const ImgPreview = {}

ImgPreview.install = Vue => {
 const ImgConstructor = Vue.extend(ImgPreviewComponent)

 const instance = new ImgConstructor()

 instance.$mount(document.createElement('div'))

 document.body.appendChild(instance.$el)

 Vue.prototype.$imgPreview = (e) => {
   instance.target = e.currentTarget
   instance.imgs = instance.target.getAttribute('data-img').split(',')
   instance.isShowImageDialog = true
 }
}

export default ImgPreview

应用也很简单:

main.js

复制代码
import imgPreview from '@/components/imgPreview'

Vue.use(imgPreview)

comments.vue 页面调用

复制代码
<el-table-column
       label="评论内容"
       header-align="center"
     >
       <template slot-scope="scope">
         <div v-html="scope.row.content"></div>
         <el-button v-if="scope.row.images.length>0" :data-img="scope.row.images" type="text" size="small" @click="$imgPreview">查看图片</el-button>
       </template>
     </el-table-column>

整个插件原理也很简单:所有的数据都放在data-img上,插件获取其中的数据,然后通过element ui的el-carousel组件轮播显示

下一篇 / vue 富文本图片懒加载

🎯 相关文章

💡 推荐文章

🕵️‍♂️ 评论 (0)