How to accessing mapState in Vuex and render it to view
10,619
Solution 1
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 :( )
Solution 2
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']) }
Related videos on Youtube
Comments
-
Alvin almost 2 years
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.
-
Ryo Shiina almost 5 yearsThe first
.then()
in yourloadPosts()
action has a typo error:response
becomesresnponse.data
after the arrow. In this casedata
isundefined
. -
Alvin almost 5 yearsI have change it but it still doesn't work
-
Ryo Shiina almost 5 yearsWhat does your first
console.log(posts)
return? -
Alvin almost 5 yearsIt return JSON data object from API endpoint
-
Ryo Shiina almost 5 yearsOkay so it might come from the asynchronous operation itself. Did you try putting a
v-if="posts.length > 0"
in the outer<div>
of your component ? It will not render until your posts data are ready.
-
-
Ryo Shiina almost 5 yearsThis is actually not an answer, but you can post it in the comments :)
-
Alvin almost 5 yearsCool, awesome! this is work for me. Additional
this.$store.dispatch("form/loadPosts");
increated()
-
trainoasis over 3 yearsNot an answer. How does one access posts in template is what was expected afaik