阅读 774

Vue3 全局注册 Socket.IO

  • 编写一个插件
// src/plugins/io.js
import io from 'socket.io-client'
export default {
    install: (app, { connection, options }) => {
        var socket = io(connection, options)
        app.config.globalProperties.$socket = socket
        app.provide('socket', socket)
    }
}
复制代码
  • 引入插件
import { createApp } from 'vue'
import App from './App.vue'
import SocketIO from './plugins/io'

const app = createApp(App)

app.use(SocketIO, {
    connection: 'ws://localhost:3200',
})

app.mount('#app')
复制代码
  • 使用插件
<template>
  <button @click="handleSendMessage">SEND</button>
</template>

<script setup>
import { inject } from "vue";

const socket = inject("socket");

socket.on("connection", (res) => {
  console.log("#connection: ", res);
});

socket.on("connected", (res) => {
  console.log("#connected: ", res);
});

socket.on("message", (res) => {
  console.log("#message: ", res);
});

const handleSendMessage = () => {
  socket.emit("message", "{ text:  '客户端发送的消息'}");
};
</script>
复制代码
文章分类
前端
文章标签