如果感觉ocx控件会破坏vue代码结构,写起来很别扭,我们可以使用iframe来封装ocx控件。

以串口控件为例,文件包括:serial.html和serial.vue

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>串口</title>
  <script>
    var mscomm_scan_value = '';
    function MSComm1_OnComm() {
      if (MSComm1.CommEvent == 2) {
        mscomm_scan_value += MSComm1.Input;
        if (mscomm_scan_value.length === 13) {
          window.parent.postMessage({ type: 'ywlsh', msg: mscomm_scan_value }, '*');
          mscomm_scan_value = '';
        }
      }
    }

    //打开端口和关闭端口
    function OperatePort() {
      if (MSComm1.PortOpen == true) { //如果打开就关闭
        try {
          MSComm1.PortOpen = false;
        } catch (ex) {
          alert(ex.message);
        }
      } else { //打开串口
        try {
          MSComm1.PortOpen = true;
        } catch (ex) {
          alert(ex.message);
        }
      }
    }
  </script>
  <script LANGUAGE=javascript FOR=MSComm1 EVENT=OnComm>
    MSComm1_OnComm();//串口事件
  </script>
</head>

<body onload="OperatePort()" onunload="OperatePort()">
  <OBJECT id="MSComm1" CLASSID="clsid:648A5600-2C6E-101B-82B6-000000000014" type="application/x-oleobject" width=0
    height=0>
    <PARAM NAME="CommPort" VALUE="10" />
    <PARAM NAME="DataBits" VALUE="8" />
    <PARAM NAME="StopBits" VALUE="1" />
    <PARAM NAME="BaudRate" VALUE="9600" />
    <PARAM NAME="Settings" VALUE="9600,N,8,1" />
    <PARAM NAME="RTSEnable" VALUE="1" />
    <PARAM NAME="DTREnable" VALUE="1" />
    <PARAM NAME="Handshaking" VALUE="0" />
    <PARAM NAME="NullDiscard" VALUE="0" />
    <PARAM NAME="ParityReplace" VALUE="?" />
    <PARAM NAME="EOFEnable" VALUE="0" />
    <PARAM NAME="InputMode" VALUE="0" />
    <PARAM NAME="InBufferSize" VALUE="1024" />
    <PARAM NAME="InputLen" VALUE="0" />
    <PARAM NAME="OutBufferSize" VALUE="512" />
    <PARAM NAME="SThreshold" VALUE="0" />
    <PARAM NAME="RThreshold" VALUE="1" />
  </OBJECT>
</body>

</html>
<template>
  <div>
    <iframe frameBorder="no" src="serial.html"></iframe>
  </div>
</template>

<script>
export default {
  mounted () {
    //绑定iframe事件消息
    window.addEventListener('message', this.iframeEvent)
  },
  destroyed () {
    //解绑iframe事件消息
    window.removeEventListener('message', this.iframeEvent)
  },
  methods: {
    iframeEvent (event) {
      if (event.data.type === 'ywlsh') {
        console.log(event.data.msg)
        window.removeEventListener('message', this.iframeEvent)
      }
    }
  }
}
</script>

iframe封装ocx控件就是通过addEventListener来和vue进行通信,这样也可以正常使用控件的事件。

下篇文章将介绍如何直接在vue中绑定ocx控件的事件。

Logo

前往低代码交流专区

更多推荐