【发布时间】:2023-02-09 15:23:01
【问题描述】:
在这里,我将展示如何在最新的 nuxt v.3 中创建和访问套接字 io 服务器,对于许多开发人员来说,由于新功能,从 .2 迁移可能很困难。
【问题讨论】:
标签: websocket socket.io nuxt.js nuxt3
在这里,我将展示如何在最新的 nuxt v.3 中创建和访问套接字 io 服务器,对于许多开发人员来说,由于新功能,从 .2 迁移可能很困难。
【问题讨论】:
标签: websocket socket.io nuxt.js nuxt3
这将创建您的套接字 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.config.ts ... modules: ['./modules/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>
【讨论】: