vuejs2 - 使用 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触发,并且我在页面加载时将第一个元素记录在终端中。然而,我在客户端的商店是空的。
我错过了什么?
解决方案
在朋友的帮助下,我们设法通过删除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));
}
}
推荐阅读
- api - 是否可以按类型过滤 GitHub REST API 事件?
- c# - 部分构建 Unity3D 编辑器扩展
- java - objectmapper 如何转换为我的对象,它是否创建了新实例
- javascript - 链接多个 promise.all() 语句
- batch-file - 用bat文件删除txt的特定部分
- python - 如果列名包含某些子字符串,如何更改列名?
- android - 如何在 Android 中显示文件目录?
- scala - Spark 中允许执行更新和删除操作的替代选项
- php - 棘轮服务器实例化:“不支持声明‘strict_types’”
- python - 在 Keras 中乘积两个 3D 张量