我正在发现 VueJS,但在查询 API 时遇到问题。 有(太多)资源,而且看起来我遇到的每个教程都有不同的方法。现在我迷路了......
该项目是一个 3 页的小展示。内容由 API 提供,每种语言都有一个端点。我想使用 VueX 来存储数据,并根据语言切换交互来更新它。
根据文档,“经典”方法已被弃用,我使用“模块”方法。不过,我认为将数据集中在存储根目录是可以的,因为只需要一次 API 调用:
/store/index.js
import axios from "axios";
// STATE - Initial values
export const state = () => ({
content: {}
});
// ACTIONS - Asynchronous operations
export const actions = () => ({
async nuxtServerInit({ commit }) {
// I will introduce the language variable later here
const response = await this.$axios.$get('https://APIURL.com/fr');
const content = response.data;
commit("setContent", content);
}
});
// MUTATIONS - Updates the state
export const mutations = {
setContent(state, content) {
state.content = content;
}
};
此时,我希望内容可供不同的页面或组件使用。
/components/A_component.vue
和/或 /pages/index.vue
...
{{ content }}
...
// LOADS the store
import { mapState } from "vuex";
// COMPUTES the values retrieval
export default {
computed: mapState(["content"])
};
但是,什么也没有显示。事实上,content
对象没有更新并且保持为空。
最佳答案
好吧,我终于找到了 bug 的出处。
actions
应导出为对象,而不是函数:
export const actions = {
async nuxtServerInit({ commit }) {
// I will introduce the language variable later here
const response = await this.$axios.$get('https://APIURL.com/fr');
const content = response.data;
commit("setContent", content);
}
};
关于vue.js - nuxtJS 与 Axios 和 VueX 的简单使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57759309/