Alvin
Alvin

Reputation: 51

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.

Upvotes: 3

Views: 16907

Answers (3)

MD Golam Rakib
MD Golam Rakib

Reputation: 144

I am using one of the following way in my applications. It depends on your requirement. You can also try.

...mapState("form", ["posts"])
or
...mapState("form", {
  posts: state => state.posts
})
or
...mapState({
  posts: state => state.form.posts
}),

Upvotes: 0

Alabura
Alabura

Reputation: 46

I'm new to vue js but you can try this in the component you want to render render the posts:

import { mapState } from 'vuex';

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

Upvotes: 2

Toyo Tomi
Toyo Tomi

Reputation: 146

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 :( )

Upvotes: 12

Related Questions