index.vue 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <template>
  2. <div>
  3. <div class="title">变频器</div>
  4. <ul class="flex-ul">
  5. <li>功率<span>:{{data.power}}</span>KW</li>
  6. <li>频率<span>: {{data.frequency}}</span>Hz</li>
  7. </ul>
  8. </div>
  9. </template>
  10. <script>
  11. import { mapState } from "vuex";
  12. export default {
  13. data() {
  14. return {
  15. data: {
  16. power: "1230",
  17. frequency: "280",
  18. },
  19. };
  20. },
  21. //注意 这个id还是待定
  22. mounted() {
  23. this.websocket = new WebSocket(`ws://${this.websocketIP}/hbase/ws/belt/id`);
  24. this.initWebSocket();
  25. },
  26. methods: {
  27. initWebSocket() {
  28. // 连接错误
  29. this.websocket.onerror = () => {
  30. console.log(
  31. "WebSocket连接发生错误 状态码:" + this.websocket.readyState
  32. );
  33. };
  34. // 连接成功
  35. this.websocket.onopen = () => {
  36. console.log(
  37. "WebSocket连接成功 状态码:" + this.websocket.readyState
  38. );
  39. };
  40. // 收到消息的回调
  41. this.websocket.onmessage = (event) => {
  42. if (JSON.parse(event.data).length) {
  43. this.changeState(JSON.parse(event.data));
  44. }
  45. };
  46. // 连接关闭的回调
  47. this.websocket.onclose = () => {
  48. console.log(
  49. "WebSocket连接关闭 状态码:" + this.websocket.readyState
  50. );
  51. };
  52. // 通过$once来监听定时器,在beforeDestroy钩子可以被清除。
  53. this.$once("hook:beforeDestroy", () => {
  54. this.websocket.close();
  55. console.log("关闭websocket连接");
  56. });
  57. },
  58. changeState(data) {
  59. this.data=data[0];
  60. console.log("数据展示为:", this.data);
  61. },
  62. close() {
  63. this.websocket.close();
  64. console.log("关闭websocket连接");
  65. },
  66. },
  67. computed: {
  68. ...mapState(["websocketIP"]),
  69. },
  70. };
  71. </script>
  72. <style scoped lang="less">
  73. .title {
  74. color: #fff;
  75. font-size: 20px;
  76. font-weight: bolder;
  77. text-align: center;
  78. margin-top: 10px;
  79. }
  80. .flex-ul {
  81. display: flex;
  82. // flex-direction: column;
  83. justify-content: center;
  84. align-items: center;
  85. list-style: none;
  86. width: 100%;
  87. flex-flow: row wrap;
  88. li {
  89. // font-size: 17px;
  90. font-size: 16px;
  91. width: -webkit-fit-content;
  92. flex: 0 1 100%;
  93. text-align: center;
  94. margin: 20px 10px 0 -10px;
  95. // line-height: 50px;
  96. color: #4adefe;
  97. }
  98. span{
  99. color: #fff;
  100. }
  101. }
  102. </style>