在vue中嵌入的html代码中图片使用v-viewer实现旋转、放大等功能

一、前情提要

本文主要实目前vue代码中,将html代码、js代码以及css代码嵌入div中,并使用html代码与vue的通信,实现双击图片,调用vue里面的方法,实现图片的旋转、放大等功能。

二、具体实现

1、要嵌入到vue代码中的部分html代码

双击图片会调用imgDbClick方法,此方法为html里面的方法。

 <img ondblclick="imgDbClick(this)" src="http:127.0.0.1/test/test.png">

2、imgDbClick方法

双击图片时会调用此方法,此方法会发起跨域通信。

/*点击图片触发*/
var imgDbClick = function (img) {
    window.parent.postMessage({
        cmd: 'dealImg',
        params: {
            url: img.src,
        }
    }, '*');	
};

3、vue中的代码

在下面的div中嵌入html代码

          <div id="showHtml">
          </div>

4、嵌入html代码

下方代码中的htmlStr为具体的html代码。

          let element = document.getElementById(activeName);
          element.innerHTML = htmlStr;

5、嵌入js代码

由于js代码存在文件服务器上,所以采用文件引入的方式。

          //动态绑定script
          let scriptElement = document.createElement("script");
          scriptElement.type = "text/javascript";
          scriptElement.src = "http://127.0.0.1/test/common_code/common.js";
          element.append(scriptElement);

6、嵌入css代码

css代码存在文件服务器上,所以采用文件引入的方式。

  let styleElement = document.createElement("link");
  styleElement.rel="stylesheet";
  styleElement.type="text/css";
  styleElement.href="http://127.0.0.1/test/common_code/common.css";
  element.append(styleElement);

7、监听html的通信

监听message,拿到图片的地址,并使用viewer来实现旋转、放大等功能

          window.addEventListener('message',(event)=>{
            const res = event.data;
            if(res.cmd =='dealImg'){
              let url =res.params.url;
              //需要引入其它文件,见8、9、10
              this.$viewerApi({
                images: [url]
              })
            }
          })

8、使用v-viewer

使用npm命令安装v-viewer

npm install v-viewer

9、全局引用

在main.js中全局引用

import 'viewerjs/dist/viewer.css'
import { api as viewerApi } from "v-viewer"
Vue.prototype.$viewerApi = viewerApi;

10、使用

imagesArr为url数组,在需要使用的地方调用即可

          this.$viewerApi({
              images: imagesArr
          })

三、实现效果

00:00

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 共1条

请登录后发表评论