基于Vue2x的图片预览插件的示例代码

2020-06-14 06:30:05易采站长站整理

本文介绍了基于Vue2x的图片预览插件的示例代码,分享给大家,具体如下:

先来看下Demo

LiveDemo

关于开发Vue插件的几种方式 (具体请移步官网)Vue官网


MyPlugin.install = function (Vue, options) {
// 1. 添加全局方法或属性
Vue.myGlobalMethod = function () {
// 逻辑...
}

// 2. 添加全局资源
Vue.directive('my-directive', {
bind (el, binding, vnode, oldVnode) {
// 逻辑...
}
...
})

// 3. 注入组件
Vue.mixin({
created: function () {
// 逻辑...
}
...
})

// 4. 添加实例方法
Vue.prototype.$myMethod = function (methodOptions) {
// 逻辑...
}
}

我采用第一种方式来编写这个插件

1.第一步创建项目

vue init webpack-simple youProjectName(你的项目名称)具体操作不在赘述

2.开始插件开发,编写index.js


import vuePictureViewer from './vue-picture-viewer'
const pictureviewer = {
install (Vue, options) {
Vue.component(vuePictureViewer.name, vuePictureViewer)
}
}

if (typeof window !== 'undefined' && window.Vue) { // 这段代码很重要
window.Vue.use(pictureviewer)
}
export default pictureviewer

3.编写vue-picture-viewer.vue也挺简单(具体可以去看源码)

4.如何使用(main.js)


import vuePictureViewer from './lib/index.js'
Vue.use(vuePictureViewer)

App.vue


<template>
<div id="app">
<vue-picture-viewer :imgData="imgUrl" :switch="true" v-if="imgUrl"></vue-picture-viewer>
</div>
</template>

<script>
export default {
name: 'app',
data () {
return {
imgUrl: [{
url:'http://p8ny46w8x.bkt.clouddn.com/test1.jpg',
name: 'test1.jpg'
},
{
url: 'http://p8ny46w8x.bkt.clouddn.com/test2.jpg',
name: 'test2.jpg'
}, {
url: 'http://p8ny46w8x.bkt.clouddn.com/test3.jpg',
name: 'test3.jpg'
},
{
url: 'http://p8ny46w8x.bkt.clouddn.com/test4.jpg',
name: 'test4.jpg'
}] }
}
}
</script>

<style>
* {
margin: 0;
padding: 0;
}
html, body {
width: 100%;
height: 100%;
}
</style>

5.打包前的配置webpack.config.js(很重要!!!)


module.exports = {
entry: './src/lib/index.js',