How do you emit an event from a nuxt plugin?

前端 未结 3 1924
傲寒
傲寒 2021-01-18 19:19

I am creating a plugin that will emit basic nuxt events triggered by sockets. The nuxt event will then be recieved and open a snackbar. When inside a component it is easy to

3条回答
  •  盖世英雄少女心
    2021-01-18 19:49

    It's not the solution I was looking for, but as a workaround I injected another instance of vue as a plugin to use as an event bus. It doesn't use the nuxt context as I initially wanted, but it works.

    import Vue from 'vue'
    
    export const bus = new Vue()
    
    export default (_context, inject) => {
    
        // Client only
        if (process.client) {
            // Event bus for plugins
            inject('bus', bus)
        }
    }
    
    
    /**
     * Socket that pops open a snackbar
     */
    export default ({ app: { $bus, $sockets } }) => {
    
        // Incoming message
        $sockets.on('message', payload => {
    
            // When we are on the messages page with the user
            if (window.location.pathname === `/messages/${payload.message.sender.username}`) {
                $bus.$emit('message-conversation', payload)
            }
            // Elsewhere, or messages with a different user
            else {
                $bus.$emit('open-snackbar', {
                    body: payload.message.body,
                    link: `/messages/${payload.message.sender.username}`,
                    user: payload.message.sender
                })
            }
        })
    
        // Incoming notification
        $sockets.on('notification', payload => {
            $bus.$emit('open-snackbar', {
                body: payload.notification.text,
                link: payload.notification.link || '/notifications',
                user: payload.notification.source
            })
        })
    }
    
    

提交回复
热议问题