How can I use websocket in vue3+ts program

Viewed 25

I want to use websocket in my vue program.I think the store is right inject, but the browser tell me injection "store" is not found.I am so sorry that I am a newcomer about vue+ts. Here is my view page,I want to check the message from serve

<script lang="ts" setup>
  import { onBeforeMount } from 'vue'
  import { useStore } from 'vuex'

  const store = useStore()
  const initSocket = () => {
    store.commit('initWebsocket')
  }
  
  onBeforeMount(() => {
    initSocket()
  })
</script>

here is my store/index.ts code

import { createStore } from 'vuex'
import { stateInt } from '../type/storeInterface'

const state: stateInt = {
  data: {},
  webSocket: new WebSocket('ws://10.253.32.125:19782'),
}

export default createStore({
  state,
  mutations: {
    initWebsocket(state) {
      state.webSocket = new WebSocket(
          // 此处填写你要连接的ws地址
        'ws://10.253.32.125:19782'
      )
      state.webSocket.onopen = function () {
        console.log('通讯开始')
        setInterval(() => {
          state.webSocket.send('1')
        }, 1000 * 60)
      }
      state.webSocket.onmessage = function (e) {
        console.log('收到的数据:', e.data)
        let data = JSON.parse(e.data)
        state.data = e.data
        console.log(data)
      }
      state.webSocket.onerror = function () {
        console.log('通讯异常')
      }
      state.webSocket.close = function () {
        console.log('连接已断开')
      }
    },
  },
})

but when i run this code, I have the following problem enter image description here

0 Answers
Related