寫插件很簡單,滿足兩個條件即可,一、基本的邏輯思路,二、熟悉插件語法要求。本次Vue插件也比較簡單,點擊“查看圖片”用輪播的方式限制用戶上傳的圖片,如圖:


項目采用的是vue-element-admin
在‘src/components’下新建‘imgPreview’文件夾,然后在該文件夾下新建‘ImgPreview.vue’,‘index.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組件輪播顯示
原文地址:http://www.ftc20.com/wordpress/2019/04/base-element-ui-plugin/
