在这里我将展示如何在最新的nuxtv.3中创建和访问socket io服务器,对于许多开发人员来说,由于新特性,从.2迁移可能会很困难。
ohfgkhjo1#
这将创建套接字io服务器
// modules/ws-server.ts import { Server } from 'socket.io' import { defineNuxtModule } from '@nuxt/kit' export default defineNuxtModule({ setup(options, nuxt) { nuxt.hook('listen', async (server) => { const io = new Server(server) nuxt.hook('close', () => io.close()) io.on('connection', (socket) => { console.log(`Socket connected: ${socket.id}`) }) }) } })
现在我们要访问前端的套接字:
// plugins/socket.io.ts import io from 'socket.io-client' export default defineNuxtPlugin(() => { const socket = io(useRuntimeConfig().url) return { provide: { io: socket } } }) ```ts Now import module & plugin into nuxt config:
// nuxt.配置文件...模块:[“./模块/ws-server”]...
Here's example of usage in component: ```vue <template> <button @click="func()" class="bt"> <slot>Button</slot> </button> </template> <script slang="ts"> export default { data: () => ({ }), methods: { func() { this.$io.emit('event_name', {}) } } } </script> <style lang="scss" scoped> .bt { background: #202225; outline: none; border: none; color: #fff; font-family: proxima-nova, sans-serif; padding: 5px 10px; border-radius: 5px; transition: 200ms; cursor: pointer; &:hover { background: #272a2e; } } </style>
1条答案
按热度按时间ohfgkhjo1#
这将创建套接字io服务器
现在我们要访问前端的套接字:
// nuxt.配置文件...模块:[“./模块/ws-server”]...