【问题标题】:Properly written init method within module action在模块操作中正确编写 init 方法
【发布时间】:2019-12-25 19:44:08
【问题描述】:

从 Nuxt.js website 我们得到异步 nuxtServerInit 方法的示例:

actions: {
  async nuxtServerInit({ dispatch }) {
    await dispatch('core/load')
  }
}

就我而言,我有模块,这就是我使用它们的方式:

import state from './state'
import * as actions from './actions'
import * as mutations from './mutations'
import * as getters from './getters'

import messages from './modules/messages'
import notifications from './modules/notifications'

export default {
  state,
  getters,
  mutations,
  actions,
  modules: {
    messages,
    notifications
  }
}

在我的基本操作中:

export default function nuxtServerInit ({ commit, getters }, { req, res }) {}

除非我添加 axios 调用,否则此方法有效。如何正确地将 async/await 添加到这种导出功能。网站上的任何地方都没有这方面的例子......

【问题讨论】:

    标签: javascript node.js vue.js nuxt.js


    【解决方案1】:

    如果您只想在nuxtServerInit 中使用async/await 和axios:

    export default function nuxtServerInit ({ commit, dispatch }, { req, res }) {
      try {
        await dispatch('core/load')     
      } catch (err) {
    
      }
    }
    

    在你的模块中:

    async load() {
      return await this.$axios....
    }
    

    【讨论】:

    • 我刚刚想出了不同的方法,你可以告诉我它是否正确:export async function nuxtServerInit ({ commit, getters }, { req, res }) { await axios .... }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    相关资源
    最近更新 更多