【发布时间】:2019-07-30 11:46:12
【问题描述】:
我在 Vue.js 上苦苦挣扎,所以我需要你的帮助。
我想做一些太简单的事情但不幸的是没有运气。在 store.js 中,我有一个 axios fetch,它从被调用的 API 返回数据。 我的下一步是在组件中传递对象。
我使用 this.$store.dispatch('loadBeers') 和突变成功地做到了,我可以在我的 html 中呈现这些项目。
但是,如果我想处理 helloworld 组件中的数据,例如进行分页和过滤 obj,该怎么办?我的逻辑告诉我,我需要将 obj 存储在一个新数组中,然后才能处理我的数据。
如何将 this.myBeers 转移到 helloworld 组件? 也许我的逻辑或我的方法不正确,所以请原谅我只是对实例有经验,但整个框架是另一个世界......
对不起我糟糕的英语,我每天都在努力提高它们。在此先感谢社区..
Store.js
import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
import VueAxios from "vue-axios";
Vue.use(Vuex);
Vue.use(VueAxios, axios);
export default new Vuex.Store({
state: {
beers: []
},
data(){
return{
myBeers:[],
}
},
actions: {
loadBeers({ commit }) {
axios
.get("https://api.punkapi.com/v2/beers")
.then(r => {
this.myBeers = r.data;
console.log(this.beers);
})
.then(beers => {
commit("SET_BEERS", beers);
});
}
},
mutations: {
SET_BEERS(state, beers) {
state.beers = beers;
}
}
});
<template>
<div class="container">
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr v-for="beer in beers" :key="beer.id">
<td>{{ beer.id }}</td>
<td>{{ beer.name }}</td>
<td>{{ beer.abv }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
name: 'HelloWorld',
data(){
return{
myBeers:[],
}
},
mounted () {
this.$store.dispatch('loadBeers')
this.myBeers=this.$store.dispatch('loadBeers')
},
computed: mapState([
'beers'
]),
methods:{
test(){
console.log(this.loadBeers);
}
}
}
</script>
【问题讨论】:
标签: javascript vue.js axios vue-router