【发布时间】:2019-08-18 20:43:42
【问题描述】:
好的,我有两个不同的组件,每个组件都会得到 Axios 响应。但我不想单独获取每个组件中的数据。这是不对的,它会导致组件分开运行......
更新 3
我对代码做了一些更改,但仍然有一些问题。我正在Store.js 中使用 Vuex 进行 axios 调用并将其导入到我的组件中。就像下面一样。
这是我的 store.js 组件;
import Vue from "vue";
import Vuex from "vuex";
var actions = _buildActions();
var modules = {};
var mutations = _buildMutations();
const state = {
storedData: []
};
Vue.use(Vuex);
const getters = {
storedData: function(state) {
return state.storedData;
}
};
function _buildActions() {
return {
fetchData({ commit }) {
axios
.get("/ajax")
.then(response => {
commit("SET_DATA", response.data);
})
.catch(error => {
commit("SET_ERROR", error);
});
}
};
}
function _buildMutations() {
return {
SET_DATA(state, payload) {
console.log("payload", payload);
const postData = payload.filter(post => post.userId == 1);
state.storedData = postData;
}
};
}
export default new Vuex.Store({
actions: actions,
modules: modules,
mutations: mutations,
state: state,
getters
});
现在将其导入Average 组件。
import store from './Store.js';
export default {
name:'average',
data(){
return{
avg:"",
storedData: [],
}
},
mounted () {
console.log(this.$store)
this.$store.dispatch('fetchDatas')
this.storedData = this.$store.dispatch('fetchData')
},
methods: {
avgArray: function (region) {
const sum = arr => arr.reduce((a,c) => (a += c),0);
const avg = arr => sum(arr) / arr.length;
return avg(region);
},
},
computed: {
mapGetters(["storedData"])
groupedPricesByRegion () {
return this.storedData.reduce((acc, obj) => {
var key = obj.region;
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj.m2_price);
return acc;
}, {});
},
averagesByRegion () {
let arr = [];
Object.entries(this.groupedPricesByRegion)
.forEach(([key, value]) => {
arr.push({ [key]: Math.round(this.avgArray(value)) });
});
return arr;
},
}
}
我可以看到存储在控制台中的数据。但也有错误。我无法正确传递myComponent 中的数据
【问题讨论】:
-
使用vuex。并将 axios 替换为服务,并在 vuex 商店中使用。
-
如果这两个组件使用相同的组件,请改用 vuex
-
@Alexander 能否请您检查一下问题,我使用了 vuex,但遇到了一些问题。
-
我猜,您还没有在主应用程序中以
Vue.use(store)的身份注入您的商店。 -
你的意思是
myComponent我需要在myComponent 中使用这个Vue.use(store)吗? @varit05
标签: vue.js vuejs2 vue-component vuex