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 ...
Home
Public
Questions
Tags
Users
Collectives
ExploreCollectives
FindaJob
Jobs
Companies
Teams
StackOverflowforTeams
–Collaborateandshareknowledgewithaprivategroup.
CreateafreeTeam
WhatisTeams?
Teams
CreatefreeTeam
CollectivesonStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
Learnmore
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
Learnmore
HowtoaccessingmapStateinVuexandrenderittoview
AskQuestion
Asked
2years,8monthsago
Modified
1year,6monthsago
Viewed
10ktimes
2
i’mtryingtoreturnalldatafromAPItomyviewswithAxiosandusingVuextostoremystate.
Thissourcecodecanreturn‘’‘console.log’’’butitcan’tpasstoview.
Ihadtrychangemounted()tochange()butitstilldon'tworking
Heremysourcecode:
In‘./store/modules/form.js’:
importVuefrom"vue";
importaxiosfrom"axios";
importVueAxiosfrom"vue-axios";
Vue.use(VueAxios,axios);
conststate={
posts:[],
};
constmutations={
setPosts(state,posts){
state.posts=posts;
}
};
constactions={
loadPosts({commit}){
axios
.get("https://jsonplaceholder.typicode.com/posts")
.then(response=>resnponse.data)
.then(posts=>{
commit("setPosts",posts);
console.log(posts);
});
}
};
exportdefault{
//namespaced:true,
state,
mutations,
actions
};
In'./store/index.js:
importVuexfrom"vuex";
importVuefrom"vue";
importformfrom"./modules/form";
importaxiosfrom"axios";
importVueAxiosfrom"vue-axios";
Vue.use(VueAxios,axios);
Vue.use(Vuex);
exportdefaultnewVuex.Store({
modules:{
form
}
});
In‘components/Posts.vue’:
ID |
Title |
Body |
{{post.id}} |
{{post.title}} |
{{post.body}} |
Thankyousomuchifyoucanhelpme.
javascriptvue.jsaxiosvuex
Share
Follow
askedJul22,2019at11:36
AlvinAlvin
4111goldbadge33silverbadges99bronzebadges
5
Thefirst.then()inyourloadPosts()actionhasatypoerror:responsebecomesresnponse.dataafterthearrow.Inthiscasedataisundefined.
– RyoShiina
Jul22,2019at12:11
Ihavechangeitbutitstilldoesn'twork
– Alvin
Jul22,2019at12:27
Whatdoesyourfirstconsole.log(posts)return?
– RyoShiina
Jul22,2019at12:33
ItreturnJSONdataobjectfromAPIendpoint
– Alvin
Jul22,2019at12:48
Okaysoitmightcomefromtheasynchronousoperationitself.Didyoutryputtingav-if="posts.length>0"intheouter
ofyourcomponent?Itwillnotrenderuntilyourpostsdataareready.
– RyoShiina
Jul22,2019at13:00
Addacomment
|
2Answers
2
Sortedby:
Resettodefault
Highestscore(default)
Datemodified(newestfirst)
Datecreated(oldestfirst)
7
I'mbeginningtothinkthatsincehe'susingmodulesheshouldtry
computed:mapState("form",["posts"]),
(Myrepistoolowtoaddacomment:()
Share
Follow
editedJul22,2019at12:57
answeredJul22,2019at12:04
ToyoTomiToyoTomi
9655bronzebadges
3
Thisisactuallynotananswer,butyoucanpostitinthecomments:)
– RyoShiina
Jul22,2019at12:12
Cool,awesome!thisisworkforme.Additionalthis.$store.dispatch("form/loadPosts");increated()
– Alvin
Jul22,2019at13:20
Notananswer.Howdoesoneaccesspostsintemplateiswhatwasexpectedafaik
– trainoasis
Jan11,2021at14:13
Addacomment
|
1
I'mnewtovuejsbutyoucantrythisinthecomponentyouwanttorenderrendertheposts:
import{mapState}from'vuex';
then
computed:{...mapState(['posts'])}
Share
Follow
editedSep5,2020at12:39
Dharman
26.4k2020goldbadges6868silverbadges120120bronzebadges
answeredSep5,2020at12:33
AlaburaAlabura
3611bronzebadge
Addacomment
|
YourAnswer
ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers.
Draftsaved
Draftdiscarded
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingEmailandPassword
Submit
Postasaguest
Name
Email
Required,butnevershown
PostYourAnswer
Discard
Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy
Nottheansweryou'relookingfor?Browseotherquestionstaggedjavascriptvue.jsaxiosvuexoraskyourownquestion.
TheOverflowBlog
AIandnanotechnologyareworkingtogethertosolvereal-worldproblems
FeaturedonMeta
WhatgoesintositesponsorshipsonSE?
StackExchangeQ&AaccesswillnotberestrictedinRussia
NewUserExperience:DeepDiveintoourResearchontheStagingGround–How...
AskWizardforNewUsersFeatureTestisnowLive
Related
1754
HowtomergetwoarraysinJavaScriptandde-duplicateitems
2
Howtotestmutationswhenusingvuexmodules
0
HowtoaccessVuexstorefromjavascript/typescriptmodulesfiles(import/export)?
3
HowtouseagoodVueXstoredesigninalargeSPA?
1
WhatistheproperwaytodoAjaxcallwithcomputedpropertiesfromVueXStore
1
Axiosinterceptor-howtoreturnresponsefromvuexstore
0
HowtoaccessVuexrootmutationfromamodule?
HotNetworkQuestions
Convertbetweengraphrepresentations
Howtogetthelistofconstanttermsoflinearequations?
Couldvideosbeauthenticatedusingprivateandpublickeys?
Isitimpolitetosendtheprofessorapre-writtenletterofrecommendationforapproval?
Sandboxoverflow
Simplequadraticfunction,butcan'tunderstandthequestion
Howtomakespacingbetweenanon-fractiontoafractionthesameasfractiontoafractioninmathmode?
Willunevenspeedberoundedupordown?
Retainingambitiousemployeewithrareskillset
Pythontoexcel
ITstaffsaidthatLinuxcannotconnecttotheschool'sInternet(EduStar)andrefusedtotry
GeometryNodes:Howtomaketubefromcurve
Combineeachelementwithalltheothersinsublists
Isthereaconventionfordocumentingaschematicwithnotes?
WhatwouldUkrainegainbydisclosingintelligenceinformationaboutPutinassassinationplans?
WhydoesahypersonicmissileneedstocruiseEarthatlowaltitudebeforehittingitsmark?
StopPipesFromPullingThroughTheWall
Howtopolitelystatemoralobjection
WhatdoestheLorentzfactorrepresent?
ArrangeaHaft-Sintable
Inthesentence"Thetablewassetforlunch"is"set"averboranadjective?
Wouldwearingfullplatearmorcauseslashingdamagetobeconvertedintobludgeoningdamage?
ConvertDateformattoinsertintoMySQLdatabase
WhatwastheethniccompositionofSovietgovernment?
morehotquestions
Questionfeed
SubscribetoRSS
Questionfeed
TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader.
lang-js
Yourprivacy
Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy.
Acceptallcookies
Customizesettings