img

基于element ui的图片预览插件

2020-11-24 0条评论 3.1k次阅读 JavaScript


写插件很简单,满足两个条件即可,一、基本的逻辑思路,二、熟悉插件语法要求。本次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组件轮播显示

🏷️ #element#vue

💬 COMMENT


🦄 支持markdown语法

👋友