之前工作中需要用到图片预览,但是没有找到合适的图片插件,于是自己写了一个贴到github上。没想到一直有人在用,小明星也到了一百多个文档,每天还有人访问文档,所以抽空把它兼容vue3,记录一下在这里。由于业务部分的代码是兼容vue3的,所以我主要记录一下vue2和vue3插件部分的区别。以上插件github地址:https://github.com/heyongshen...gitee:https://gitee.com/ihope_top/h...文档地址:https://heyongsheng.github.io/#/为了方便,我把vue2和vue3的兼容性放在一个文件里做逻辑处理,不用下载不同的版本先看前面的索引配置文件importVuefrom"vue";importVueToastfrom"./hevue-img-preview.vue";constToastConstructor=Vue.extend(VueToast);让instancelethevueImgPreviewConfigconstImgPreview=(options={})=>{if(typeofoptions==='string'){options={url:options};}options.show=true//优先本地配置,其次是全局配置})instance=newToastConstructor({data:options})instance.$mount()让dom=instance.$eldocument.body.appendChild(dom)returninstance};constinstall=(Vue,opts={})=>{hevueImgPreviewConfig=optsVue.prototype.$hevueImgPreview=ImgPreview;};if(typeofwindow!=="undefined"&&window.Vue){//window.Vue.use(安装);安装(window.Vue)}导出默认安装;废弃Vue.extend和vue.prototype.xxx=xxx在vue3中,Vue.extend被废弃,取而代之的是createApp,这里可以判断用户使用的vue版本,从而使用不同的导入方式。另外,我们以前使用的vue.prototype.xxx=xxx方式不再推荐,改为app.config.globalProperties.xxx=xxx,因为js规定必须在head引入import,而我们需要先判断vue的版本,再决定导入方式,所以我们可以改用import()方法。注意这是一个异步函数,所以install部分的代码需要修改如下0]if(vueVersion>2){let{createApp}=awaitimport("vue");imgApp=createApp(VueToast)app.config.globalProperties.$hevueImgPreview=ImgPreview;}else{let_vue=await(awaitimport("vue")).default;安慰剂e.log(_vue);imgApp=_vue.extend(VueToast)_vue.prototype.$hevueImgPreview=ImgPreview;}};在vue3中,同一个插件将无法重复注册同一个插件多次注册,即使调用多次,该插件也只会被注册一次。所以我们将无法重复生成实例。我的做法是第一次生成实例后把生成的logo存起来,第二次执行的时候不生成(因为不能生成两次),而是复用我对vue3不熟悉,这个的描述段落可能不正确,请指正。另外,在vue3中,$mount()不再支持无参调用,所以整体代码修改如下})=>{if(typeofoptions==='string'){options={url:options};}//优先局部配置,其次进行全局配置(vueVersion>2){if(!imgApp.hevueImgPreviewInstalled){constparent=document.createElement('div')instance=imgApp.mount(parent)imgApp.hevueImgPreviewInstalled=trueletdom=instance.$eldocument.body.appendChild(dom)}Object.keys(options).map(name=>{instance[name]=options[name]})}else{instance=newimgApp({data:options})实例.$mount()让dom=instance.$eldocument.body.appendChild(dom)}instance.show()返回实例}constinstall=async(app,opts={})=>{hevueImgPreviewConfig=optsvueVersion=app.version.split(".")[0]if(vueVersion>2){let{createApp}=awaitimport("vue");imgApp=createApp(VueToast)app.config.globalProperties.$hevueImgPreview=ImgPreview;}else{let_vue=await(awaitimport("vue")).default;控制台日志(_vue);imgApp=_vue.extend(VueToast)_vue.prototype.$hevueImgPreview=ImgPreview;}};if(typeofwindow!=="undefined"&&window.Vue){install(window.Vue)}exportdefaultinstall;本人也是vue3新手,希望对你有所帮助,而且这个插件会持续更新,欢迎有需要的朋友收藏
