Nuxt Sockets
Nuxt wrapper for Vue 3 Perfect Scrollbar
Overview
Nuxt Sockets implements bidirectional sockets communication between Nitro and Nuxt.
It supports named channels making it ideal for plugin authors.
const socket = useSocketServer('my-plugin')
socket.send('ping!')
const socket = useSocketClient('my-plugin', ({ channel: string, data: any }) => {
console.log(data)
})
Demo
To view the demo live on StackBlitz:
To run the demo locally:
npm run dev
Quick Setup
Installation:
npm install --save @davestewart/nuxt-sockets
Configuration:
export default defineNuxtConfig({
modules: [
'@davestewart/nuxt-sockets'
],
})
Usage
Server
Here's how you might set up the server to watch some files, then report them to the frontend:
import { createStorage } from 'unstorage'
import { useSocketServer } from '@davestewart/nuxt-sockets'
export default function (options, nuxt) {
const socket = useSocketServer('my-plugin')
const storage = createStorage(dirname)
storage.watch(function (event, key) => {
socket.send({ event, key })
})
socket.onMessage(({ data }) => {
console.log('message:', data)
})
}
Client
The client should take the same name as the server, so calls are sent between the two, and they don't clash with any other services using sockets.
export default defineNuxtPlugin(async () => {
if (process.client) {
const socket = await useSocketClient('my-plugin', ({ data }) => {
console.log('file changed', data)
})
window.addEventListener('click', () => {
socket.send('user clicked')
})
}
})
Alternative setups
You can create a Socket instance in several ways:
const socket = useSocketServer()
const socket = useSocketServer('some-name')
const socket = useSocketServer('some-name', ({ channel, data }) => {
console.log({ channel, data })
})
const socket = useSocketServer('some-name').addHandler<Bar>('foo', ({ data }) => {
console.log(data.baz)
})
The library also has some generic typing, so you can hint the return data type:
type Foo = { foo: string }
type Bar = { bar: string }
type Baz = { baz: string }
const socket = useSocketServer<Foo>('plugin', ({ data }) => {
console.log(data.foo)
})
const socket = useSocketServer<SomeClass>('plugin', ({ data }) => {
console.log(data.bar)
})
const socket = useSocketServer<SomeClass>('plugin').addHandler<Bar>('foo', ({ data }) => {
console.log(data.baz)
})
Filtering
The module supports basic filtering, but this may be taken out in the next version.
Development
To develop the module:
npm run dev
npm run release