javascript - 如何在 Vuex 中访问 mapState 并将其渲染以查看
问题描述
我正在尝试使用 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"]),
(我的代表太低,无法添加评论:()
推荐阅读
- vim - 尽可能快地使 w0rp 异步 Lint 引擎“ALE”?
- powerapps - PowerApps interate through list updates
- javascript - React 组件设置状态未按预期工作
- python - 将 JSON 元素分隔到 pandas 数据框的列中
- image - 在二值化图像中分离交叉段
- android - 无法打开/qemu.conf,错误:2
- variables - 如何气流变量的值包含外来字符?
- python - 按分隔符拆分列并删除扩展列
- vsphere - cloud-init 用户数据传递到的 linux 文件位置是什么?
- python - Python3.7 转换逗号分隔的日期时间