首页 > 解决方案 > 使用 Nuxt.js 在 Vuex 中预取 api 数据

问题描述

我正在尝试在客户端启动之前预先获取一些数据并更新 Vuex。

store/index.js

export const state = () => ({});
export const getters = {};
export const actions = {
  async nuxtServerInit ({ dispatch }) {
    await dispatch('nasa/getImages');
  }
};

store/moduleName.js

import fetch from 'node-fetch';

export const state = () => ({
  images: []
});

export const mutations = {
  storeImages(state, data) {
    state.images = [];
    state.images.push(...data);
    console.log(state.images[0]); <- this logs in the terminal
  }
}

export const actions = {
  getImages(store) {
    return fetch('api/url').then(response => {
      response.json().then(function(data) {
          store.commit('storeImages', data.collection.items.slice(0, 24));
      });
    });
  }
}

我的突变由nuxtServerInit触发,并且我在页面加载时将第一个元素记录在终端中。然而,我在客户端的商店是空的。

我错过了什么?

标签: vuejs2vuexnuxt.jsprefetch

解决方案


在朋友的帮助下,我们设法通过删除node-fetch并将axios添加到 Vuex 来解决这个问题。

唯一的改变是store/moduleName.js现在看起来像:

import Axios from 'axios'

export const state = () => ({
  images: []
});

export const mutations = {
  storeImages(state, data) {
    state.images.push(...data);
  }
}

export const actions = { 
  async getImages(store) {
    let res = await Axios.get('api/url');
    store.commit('storeImages', res.data.collection.items.slice(0, 24));
  } 
}

推荐阅读