您如何从nuxt插件发出事件?

时间:2019-09-28 00:51:58

标签: nuxt.js nuxt

我正在创建一个插件,该插件将发出由套接字触发的基本nuxt事件。然后将接收nuxt事件,并打开一个小吃店。在组件内部时,使用$nuxt

很容易发送和接收事件。
this.$nuxt.$on('open-snackbar', this.handler)
this.$nuxt.$emit('open-snackbar', options)

但是我如何尝试在插件中执行此操作,因此它不与任何页面绑定,而是存在于整个应用程序中。我似乎无法弄清楚如何从所说的插件发出它:

export default (context) => {
    console.log(context)
    console.log(context.$emit)
    console.log(context.emit)
    console.log(context.$nuxt)
    console.log(context.app.emit)
    console.log(context.app.$nuxt)
}

context.app似乎是正确的对象,但似乎不起作用。有什么想法吗?

3 个答案:

答案 0 :(得分:2)

您可以在plugin.js文件中使用类似的内容,该插件将使用window.$nuxt.$emit,该功能在客户端可用

export default function (context) {
    $nuxt.$emit('event-to-emit')
}

答案 1 :(得分:1)

我想出了另一种方法,通过使用Vue本身并使用documentation

创建手动事件总线

在我的情况下,我有一个全局axios拦截器来检查响应的状态码401,这意味着用户的会话已过期,然后向他们显示通知。


// my-plugin.js
import Vue from 'vue'

export default function ({ $axios, app }, inject){

  inject('eventHub', new Vue()); // this is the same as Vue.prototype.$eventHub = new Vue()

  // checking for status 
    $axios.onError((error) => {
    const code = parseInt(error.response && error.response.status)
    if (code === 401) {
      app.$auth.logout() // logout if errors have happened
      app.$eventHub.$emit('session-expired')
    }
  })
}

现在可以在上下文和任何Vue实例中访问事件总线

// login.vue

export default{
  data(){
    // data
  },
  created(){
    this.$eventHub.$once('session-expired', ()=> {
    this.showAlert()
  })
  },
  methods: {
    showAlert(){
      // display notifcations
    }
  }
}

答案 2 :(得分:0)

这不是我一直在寻找的解决方案,但是作为一种解决方法,我注入了另一个vue实例作为插件来用作事件总线。它不像我最初想要的那样使用nuxt上下文,但是它可以工作。

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
        })
    })
}