猿问

使用 SSR 时,Nuxt Store 的初始状态未定义

我为我的索引页面创建了一个 Nuxt 存储,目的是初始化状态并从 API 获取一些数据以改变状态。


这是我商店的代码,包括初始状态、突变和操作。


import Axios from "axios";


//a controller has a store that it interfaces with


// set initial state of the store

const initState = () => ({

  message: "init"

})


// make the state usable from other components

export const state = initState


//when you need to change the state

//for mutations you do commits

export const mutations = {

  setMessage(state, message) {

    state.message = message

  }, //can define more functions here

  reset(state) {

    Object.assign(state, initState())

  }

}


//when you have to do API calls (async)

//commit parameter allows us to invoke the mutation functions

//for actions you do dispatch

export const actions = {

    async nuxtServerInit({commit}) {

      const message = await Axios.get("http://localhost:5000/api/home").data;

      console.log(message);

      commit("setMessage", message) //put name of mutation as parameter + payload

    }

}

在我的 index.vue 文件中,我从 vuex 导入所需的函数并映射状态。


import Logo from '~/components/Logo.vue'

import VuetifyLogo from '~/components/VuetifyLogo.vue'

import Axios from "axios";

import {mapState, mapActions, mapMutations} from 'vuex'


export default {

  components: {

    Logo,

    VuetifyLogo

  },

  computed: mapState({

    message: state => state.message

  }),

  methods: mapMutations([

    "reset",

    "setMessage"

  ])

但是,当我加载页面(使用 Vue 开发工具)时,我的状态开始未定义。我可以通过“重置”方法改变状态,但我的 API 没有被调用来获取数据。我在控制台中没有收到任何错误,所以我不确定是什么原因造成的。我的 API 也已启动并正在运行。


如何确保在加载页面时调用 nuxtServerInit 操作?


跃然一笑
浏览 140回答 1
1回答

MMMHUHU

我相信这个nuxtServerInit动作被恰当地调用了。我敢打赌,它message的值始终为未定义,因为 Axios.get("http://localhost:5000/api/home")返回的 promise 没有属性data。您必须先等待结果,然后获取它的数据。// note extra parenthesesconst message = await (Axios.get("http://localhost:5000/api/home")).data;此外,您可能希望将 axios 调用包装在 try-catch 中,否则如果调用失败,您将获得带有堆栈跟踪的默认 Nuxt 错误页面。  async nuxtServerInit ({ commit }: any) {    try {      const message = (await Axios.get('http://localhost:5000/api/home')).data;      console.log(message);      commit('setMessage', message); // put name of mutation as parameter + payload    } catch (error) {      // you could redirect to custom error page for instance      console.error(error);    }  }
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答