第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 SSR 時,Nuxt Store 的初始狀態(tài)未定義

使用 SSR 時,Nuxt Store 的初始狀態(tài)未定義

躍然一笑 2023-04-14 17:17:22
我為我的索引頁面創(chuàng)建了一個 Nuxt 存儲,目的是初始化狀態(tài)并從 API 獲取一些數(shù)據(jù)以改變狀態(tài)。這是我商店的代碼,包括初始狀態(tài)、突變和操作。import Axios from "axios";//a controller has a store that it interfaces with// set initial state of the storeconst initState = () => ({  message: "init"})// make the state usable from other componentsexport const state = initState//when you need to change the state//for mutations you do commitsexport 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 dispatchexport 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 導入所需的函數(shù)并映射狀態(tài)。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 開發(fā)工具)時,我的狀態(tài)開始未定義。我可以通過“重置”方法改變狀態(tài),但我的 API 沒有被調用來獲取數(shù)據(jù)。我在控制臺中沒有收到任何錯誤,所以我不確定是什么原因造成的。我的 API 也已啟動并正在運行。如何確保在加載頁面時調用 nuxtServerInit 操作?
查看完整描述

1 回答

?
MMMHUHU

TA貢獻1834條經(jīng)驗 獲得超8個贊

我相信這個nuxtServerInit動作被恰當?shù)卣{用了。我敢打賭,它message的值始終為未定義,因為 Axios.get("http://localhost:5000/api/home")返回的 promise 沒有屬性data。您必須先等待結果,然后獲取它的數(shù)據(jù)。


// note extra parentheses

const 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);

    }

  }


查看完整回答
反對 回復 2023-04-14
  • 1 回答
  • 0 關注
  • 155 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號