WebsocketTest.vue 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <template>
  2. <div>
  3. <input v-model="message">
  4. <button @click="send">发消息</button>
  5. <div v-html="html">
  6. </div>
  7. </div>
  8. </template>
  9. <script>
  10. export default {
  11. name: "WebsocketTest",
  12. data () {
  13. return {
  14. path:"ws://1ce51be55193.ngrok.io/ws/",
  15. socket:"",
  16. message:'',
  17. html:''
  18. }
  19. },
  20. mounted () {
  21. // 初始化
  22. this.init()
  23. },
  24. methods: {
  25. init: function () {
  26. if(typeof(WebSocket) === "undefined"){
  27. alert("您的浏览器不支持socket")
  28. }else{
  29. // 实例化socket
  30. this.socket = new WebSocket(this.path)
  31. // 监听socket连接
  32. this.socket.onopen = this.open
  33. // 监听socket错误信息
  34. this.socket.onerror = this.error
  35. // 监听socket消息
  36. this.socket.onmessage = this.getMessage
  37. }
  38. },
  39. open: function () {
  40. console.log("socket连接成功")
  41. },
  42. error: function () {
  43. console.log("连接错误")
  44. },
  45. getMessage: function (msg) {
  46. console.log(msg.data)
  47. this.html = this.html+"<div>"+msg.data+"</div>"
  48. },
  49. send: function () {
  50. this.socket.send(this.message)
  51. },
  52. close: function () {
  53. console.log("socket已经关闭")
  54. }
  55. },
  56. destroyed () {
  57. // 销毁监听
  58. this.socket.onclose = this.close
  59. }
  60. }
  61. </script>
  62. <style>
  63. </style>