首页 > 解决方案 > 如何在 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>

如果你能帮助我,非常感谢。

标签: javascriptvue.jsaxiosvuex

解决方案


我开始认为,既然他正在使用modules,他应该尝试

computed: mapState("form", ["posts"]),

(我的代表太低,无法添加评论:()


推荐阅读