Nuxt Js 事件触发两次

Mbe*_*han 2 vue.js vuejs2 nuxt.js vue-events

我正在使用 Nuxt js SSR 来构建一个应用程序,我安装了 Vue 事件插件,但是当我发出一个事件时,它在侦听器上运行两次。创建的钩子也运行两次。

使用的模块:Axios、Auth、Toast

子组件

methods: {
  initPlaylist(songs) {
    console.log(songs)
  }
},
mounted () {
  this.$events.$on('playAll', data => {
    this.initPlaylist(data.songs) //runs twice
  })
}
Run Code Online (Sandbox Code Playgroud)

父组件

method () {
    playAll (songs) {
      this.$events.$emit('playAll', songs)
  }
 }
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?我需要你的帮助。

小智 5

也许您必须仅在客户端调用该父级的方法。

您可以编写这样的代码来防止在服务器端发出:

methods: {
  playAll(songs) {
    if (process.server) return

    this.$events.$emit('playAll', songs)
  }
}
Run Code Online (Sandbox Code Playgroud)

或者不要在服务器端调用 playAll 方法。(例如:创建、安装...)