Nuxt.js 使用 nuxtServerInit 和 Vuex 加载数据服务器端

Nuxt.js Loading data serverside with nuxtServerInit and Vuex

目前我正在为职位空缺申请存储数据。 对于后端,我使用 Laravel,对于前端,我使用 Nuxt.js 我是 Nuxt 的新手,所以我有点卡在以下问题上。

我有一个用于创建名为 new-job.vue 的新职位空缺的页面。我还创建了一个名为 jobs.js 的商店来处理状态。

在 new-job.vue 上,我有一个表格,其中的数据必须在表格 starts.Like 之前的列表中呈现,这是所有国家/地区的列表等。为了让我 select 他们在表格中。

此时我在 new-job.vue:

的导出默认值中使用 asyncData
<script>
export default {

    asyncData(context) {
        return context.app.$axios
            .$get('jobs/create')
            .then(data => {
                //context.store.dispatch('jobs/getTypes', data.types)
                context.store.dispatch('jobs/getPlatforms', data.platforms)
                context.store.dispatch('jobs/getCountries', data.countries)data.branches)

                // return {
                //     loadedPost: { ...data, id: context.params.postId }
                // }composer required barr
            })
            .catch(e => context.error(e))
    },
     computed: {
         types () { return this.$store.state.jobs.types },
         platforms () { return this.$store.state.jobs.platforms },
         countries () { return this.$store.state.jobs.countries },

    },
}

asyncData 方法有效,类型、平台和国家/地区的列表被数据库中的数据填充,Vuex 存储中的状态得到更新。 .只有数据在客户端呈现。

我更喜欢在服务器端加载此数据,所以我正在查看 nuxtServerInit。只有有人可以向我解释我如何才能做到这一点。

我在 new-job.vue:

的导出默认值中放置了一个异步调用
     async nuxtServerInit ({ commit, state }, { app }) {
        let res = await axios.get(`jobs/create`)

        console.log(res)
        commit('setPlatforms', res.data.platforms)
        commit('setTypes', res.data.types)
        commit('setCountries', res.data.countries)
    },

我在 jobs.store 的变更中创建了提交,但状态没有更新。

我做错了什么and/or我错过了什么?

或者另一个问题,nuxtServerInit 是正确的选择吗?或者在客户端加载这些数据列表没什么大不了的?

更新:

我对商店使用模块模式,所以我创建了一个名为 jobs.js 的商店。在此文件中,我也尝试调用 nuxtServerInit,但没有得到任何响应。

nuxtServerInit(vuexContext, context) {
    return context.app.$axios
        .$get('jobs/create')
        .then(data => {
            console.log(data)
        })
        .catch(e => context.error(e))
},

来自 nuxtServerInit API Nuxt.js 文档中的参考:

If the action nuxtServerInit is defined in the store, Nuxt.js will call it with the context (only from the server-side).

换句话说,它是仅在 store/index.js 文件中可用的保留存储操作,如果已定义,将在呈现请求的路由之前在服务器端调用。

页面中只有 asyncDatafetch 方法可用。