【发布时间】:2019-11-30 09:12:32
【问题描述】:
我正在尝试使用 Axios 将 API 中的所有数据返回到我的视图中,并使用 Vuex 来存储我的状态。 此源代码可以返回“console.log”,但无法传递给视图。
我曾尝试将mounted() 更改为change(),但它仍然无法正常工作
这是我的源代码: 在‘./store/modules/form.js’中:
import Vue from "vue";
import axios from "axios";
import VueAxios from "vue-axios";
Vue.use(VueAxios, axios);
const state = {
posts: [],
};
const mutations = {
setPosts(state, posts) {
state.posts = posts;
}
};
const actions = {
loadPosts({ commit }) {
axios
.get("https://jsonplaceholder.typicode.com/posts")
.then(response => resnponse.data)
.then(posts => {
commit("setPosts", posts);
console.log(posts);
});
}
};
export default {
//namespaced: true,
state,
mutations,
actions
};
在 './store/index.js :
import Vuex from "vuex";
import Vue from "vue";
import form from "./modules/form";
import axios from "axios";
import VueAxios from "vue-axios";
Vue.use(VueAxios, axios);
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
form
}
});
在“组件/Posts.vue”中:
<template>
<div>
<div class="container">
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Body</th>
</tr>
</thead>
<tbody>
<tr v-for="post in posts" :key="post.id">
<td>{{ post.id }}</td>
<td>{{ post.title }}</td>
<td>{{ post.body }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<script>
import { mapState } from "vuex";
export default {
name: "PostsPage",
computed: mapState(["posts"]),
mounted() {
this.$store.dispatch("loadPosts");
},
};
</script>
如果你能帮助我,非常感谢。
【问题讨论】:
-
loadPosts()操作中的第一个.then()存在拼写错误:箭头后的response变为resnponse.data。在这种情况下,data是undefined。 -
我改了还是不行
-
你的第一个
console.log(posts)返回什么? -
从 API 端点返回 JSON 数据对象
-
好的,它可能来自异步操作本身。您是否尝试在组件的外部
<div>中添加v-if="posts.length > 0"?在您的帖子数据准备好之前,它不会呈现。
标签: javascript vue.js axios vuex