我试图调用api,并将数据保存在news对象中。 我遇到的问题是,我无法在组件Home.vue中访问对象新闻的数据
store.js
import Vue from "vue";
import Vuex from "vuex";
import {API_KEY} from '@/config/secrets.js'
import axios from 'axios';
Vue.use(Vuex);
export default new Vuex.Store({
state:{
news: [],
},
mutations: {
},
actions: {
getData(){
console.log('fetch data');
var header = new Headers();
var config = {
method: 'GET',
headers: header,
mode: 'cors',
cache: 'default'
}
axios('https://newsapi.org/v2/top-headlines?country=us&apiKey=' + API_KEY , config).then(responde =>{
console.log(responde);
this.news = responde.data;
})
}
},
getters:{
},
});
Home.vue 我想在此组件中显示对api发出的请求的数据
<template>
<div>
<h1>Home Page</h1>
<ul>
<li v-for="(content , index) in news" :key="index">
{{content}}
</li>
</ul>
</div>
</template>
<script>
import {mapActions , mapState, mapGetters} from 'vuex'
export default{
computed: mapState(['news']),
created: mapActions(['getData'])
}
</script>
我设法通过以下方式解决了问题 首先,添加一个布尔变量:
loading: true
然后在 store.js 中,他添加了以下内容:
mutations:{
updateNews(state, posts){
state.news = posts;
},
loadingState (state, loading){
state.loading = loading;
}
},
在函数getData中,我编写了以下内容:
commit ('updateNews', responde.data.articles);
commit ('loadingState', false);
在Home.vue组件中,进行了以下更改:
<script>
import {mapActions, mapState} from 'vuex';
export default {
computed: mapState (['news', 'loading']),
created (){
this.$store.dispatch ('getData');
}
}
</script>