我正在尝试使用 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>
如果您能帮助我,非常感谢。
我开始认为既然他正在使用
modules
他应该尝试
computed: mapState("form", ["posts"]),
(我的代表太低,无法添加评论:( )
我是 vue js 新手,但你可以在要渲染帖子的组件中尝试这个:
import { mapState } from 'vuex';
然后
computed: { ...mapState(['posts']) }
我在我的应用程序中使用以下方式之一。这取决于您的要求。你也可以尝试一下。
...mapState("form", ["posts"])
or
...mapState("form", {
posts: state => state.posts
})
or
...mapState({
posts: state => state.form.posts
}),