【问题标题】:How I can call NuxtServerInit correctly?如何正确调用 NuxtServerInit?
【发布时间】:2021-04-26 09:21:06
【问题描述】:

当我尝试在 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
  }
}

pages/news/index.vue

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

【问题讨论】:

  • Nuxt 配置为什么mode
  • @tony19 默认:通用,ssr false

标签: vue.js nuxt.js vuex


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-23
    • 2019-09-29
    • 2020-08-25
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    相关资源
    最近更新 更多