global.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import Vue from 'vue'
  2. import store from '@/vendors/vuex'
  3. // import router from './router'
  4. // 2.新创建一个vue实例
  5. const v = new Vue()
  6. export default {
  7. ws: {},
  8. websocket: '',
  9. setWs: function(newWs) {
  10. this.ws = newWs
  11. },
  12. whetherWebSocket: function() {
  13. var that =this
  14. if ('WebSocket' in window) {
  15. if (process.env.NODE_ENV === 'production') {
  16. that.websocket = new WebSocket('wss://www.zthymaoyi.com/wss/websocket/?adminId=84f62127b7384dcdbaeaddfe460329fc' )
  17. }
  18. else {
  19. that.websocket = new WebSocket('ws://localhost:3000/')
  20. }
  21. that.initWebSocket()
  22. } else {
  23. alert('当前浏览器不支持websocket')
  24. }
  25. },
  26. initWebSocket: function() {
  27. // 连接错误
  28. this.websocket.onerror =evt => {
  29. console.log('WebSocket连接发生错误 状态码:' + this.websocket.readyState)
  30. }
  31. // 连接成功
  32. this.websocket.onopen = evt => {
  33. console.log('WebSocket连接成功 状态码:' + this.websocket.readyState)
  34. }
  35. // 收到消息的回调
  36. this.websocket.onmessage = event => {
  37. // 根据服务器推送的消息做自己的业务处理
  38. console.log('服务端返回:' + event.data)
  39. var msg = event.data.split('$')
  40. var that = this
  41. // document.getElementsByClassName('app-container').reload()
  42. v.$notify.warning({
  43. title: '新消息提醒',
  44. message: msg[0],
  45. duration: 0,
  46. onClick() {
  47. this.$router.push({
  48. path: msg[1] }) // 你要跳转的路由 还可以传参 当然也可以通过其他方式跳转
  49. }
  50. })
  51. // console.log(router)
  52. var currentPage = this.$router.history.current.path
  53. console.log(currentPage, 'currentPage')
  54. this.$router.push({ path: '/' })
  55. console.log('执行成功1')
  56. this.$router.push({ path: currentPage,
  57. query: {
  58. params: Date()
  59. }})
  60. console.log('执行成功')
  61. }
  62. // 连接关闭的回调
  63. this.websocket.onclose = evt => {
  64. console.log('WebSocket连接关闭 状态码:' + this.websocket.readyState)
  65. }
  66. // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
  67. window.onbeforeunload = this.onbeforeunload
  68. }
  69. }