【问题标题】:How to accessing mapState in Vuex and render it to view如何在 Vuex 中访问 mapState 并将其渲染以查看
【发布时间】: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。在这种情况下,dataundefined
  • 我改了还是不行
  • 你的第一个console.log(posts)返回什么?
  • 从 API 端点返回 JSON 数据对象
  • 好的,它可能来自异步操作本身。您是否尝试在组件的外部&lt;div&gt; 中添加v-if="posts.length &gt; 0"?在您的帖子数据准备好之前,它不会呈现。

标签: javascript vue.js axios vuex


【解决方案1】:

我是 vue js 新手,但您可以在要渲染的组件中尝试此操作:

import { mapState } from 'vuex';

那么 computed: { ...mapState(['posts']) }

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 这其实不是一个答案,但你可以把它贴在 cmets 中:)
    • 酷,太棒了!这对我来说是工作。 created() 中的附加 this.$store.dispatch("form/loadPosts");
    • 不是答案。如何在模板中访问帖子是预期的 afaik
    猜你喜欢
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    • 2019-09-25
    相关资源
    最近更新 更多