Search code examples
javascriptvue.jsaxiosvuex

How to accessing mapState in Vuex and render it to view


i’m trying to return all data from API to my views with Axios and using Vuex to store my state. This source code can return ‘’‘console.log’’’ but it can’t pass to view.

I had try change mounted() to change() but it still don't working

Here my source code : In ‘./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
};

In './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
  }

});

In ‘components/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>

Thank you so much if you can help me.


Solution

  • I'm beginning to think that since he's using modules he should try

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

    (My rep is too low to add a comment :( )