码迷,mamicode.com
首页 > Web开发 > 详细

Vue websocket编程

时间:2019-06-30 23:11:41      阅读:428      评论:0      收藏:0      [点我收藏+]

标签:bottom   create   hat   init   input   new   code   成功   between   

<template>
  <div class="dashboard-container">
    <el-row type="flex" justify="space-between">
      <el-col :span="8">
        <el-input v-model="sendMessage"></el-input><el-button plain @click="send">发送</el-button>
      </el-col>
    </el-row>
    <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="txtMessage"></el-input>
  </div>
</template>

<script>

export default {
  name: ‘chat‘,
  data() {
    return {
      sendMessage: ‘‘,
      txtMessage: ‘‘,
      path: ‘ws://10.211.55.3:6690/Echo‘,
      socket: ‘‘
    }
  },
  mounted() {
    // 初始化
    this.init()
  },
  created() {
  },
  methods: {
    init: function() {
      if (typeof (WebSocket) === ‘undefined‘) {
        alert(‘您的浏览器不支持socket‘)
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.path)
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
      }
    },
    open: function() {
      console.log(‘socket连接成功‘)
    },
    error: function() {
      console.log(‘连接错误‘)
    },
    getMessage: function(msg) {
      this.txtMessage = msg.data
      console.log(msg.data)
    },
    send: function() {
      this.socket.send(this.sendMessage)
    },
    close: function() {
      console.log(‘socket已经关闭‘)
    }
  },
  destroyed() {
    // 销毁监听
    this.socket.onclose = this.close
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.dashboard-container {
  padding-top: 1px;
  padding-left: 10px;
  background-color: rgb(240, 242, 245);
  // .chart-wrapper {
  //   background: #fff;
  //   padding: 16px 16px 0;
  //   margin-bottom: 32px;
  // }
}
</style>

 

Vue websocket编程

标签:bottom   create   hat   init   input   new   code   成功   between   

原文地址:https://www.cnblogs.com/hwubin5/p/11111657.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!