首页 > 解决方案 > 如何正确调用 NuxtServerInit?

问题描述

当我尝试在 Vuex 商店上使用 nuxtServerInit 调用 rest api 时,它不会调用,但如果在组件或页面上调用 rest api,它就可以工作。

存储/index.js

 import axios from 'axios'

export const state = () => ({
  news: [],
})

export const mutations = {
  SET_NEWS(state, posts) {
    state.news = posts
  }
}


export const actions = {
 async nuxtServerInit({ commit }, ctx) {
   const res = await axios.get('https://api/news.json')
      commit('SET_NEWS', res.data)
  },
}

export const getters = {
  getNews(state) {
    return state.news
  }
}

页面/新闻/index.vue

computed: {
 getNews() {
  return this.$store.getters.getNews
 }
}

标签: vue.jsnuxt.jsvuex

解决方案


尝试在您的 vuex 操作中像这样调用您的 API:

export const actions = {
    async nuxtServerInit({ commit }, { req }) {
        const res = (await this.$axios.$get('https://api/news.json')).data
        commit('SET_NEWS', res)
    },
}

推荐阅读