vue3使用socketio的简单例子
vue3使用socketio的简单例子
·
后端是使用的springboot,socketio版本为1.7.11
<dependency>
<groupId>com.corundumstudio.socketio</groupId>
<artifactId>netty-socketio</artifactId>
<version>1.7.11</version>
</dependency>
由于后端版本问题,前端socketio安装版本不能太高,不然就会连接不上,这个问题也是查了很久才发现是版本问题
npm install socket.io-client@2.3.1
io.js
import io from 'socket.io-client'
const socket = io('http://127.0.0.1:9096', {
query: {},
transports: ['websocket', 'polling'],
timeout: 5000,
})
export default socket
mian.js中引用
import { createApp } from 'vue'
import socket from './utils/io'
const app = createApp(App);
app.mount('#app')
app.config.globalProperties.$socket = socket;
页面中使用
<script lang="ts">
import {defineComponent,ref,getCurrentInstance,onMounted,onUnmounted } from 'vue'
export default defineComponent({
setup(){
const { proxy }: any = getCurrentInstance()
onMounted(() => {
proxy.$socket.on('connect',()=>{
console.log('socketio-connect')
})
proxy.$socket.on('message',(data) =>{
console.log(data)
});
});
onUnmounted(() => {
proxy.$socket.removeAllListeners('connect');
proxy.$socket.removeAllListeners('message');
});
let sendMessage = ()=>{
console.log('发送消息')
proxy.$socket.emit('message', {
msgContent: "你好!" + new Date()
});
}
return {
sendMessage
}
}
})
</script>
有问题的地方欢迎指出
更多推荐
已为社区贡献1条内容
所有评论(0)