vue.js - 从相同的axios到不同的组件,VueJS

标签 vue.js vuejs2 vue-component vuex

好的,我有两个不同的组件,每个组件都会得到 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 中的数据

/image/J6mlV.png

最佳答案

如果你不想使用vuex来分发数据,也许你可以尝试eventBus,当你从axios获取数据时,respose @emit事件并在另一个组件中@此事件

关于vue.js - 从相同的axios到不同的组件,VueJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55391493/

相关文章:

javascript - 如何将计算参数从一个 Vue 组件传递到另一个组件?

vue.js - 如何在vue中全局制作数据、方法和计算?

javascript - 将 json 传递给 Vue 组件并循环

javascript - 从父组件向 VeeValidate 错误包添加错误并从子组件监听

javascript - Vue 绑定(bind)将数据发送到表

javascript - 无法在 vuetify 对话框的字符串中插入换行符

javascript - Vue.js 标记为无效 HTML

vue.js - Vuejs - 如何在使用插槽时渲染子组件的 vnode

laravel - 从 vue 组件的公共(public)文件夹中导入 js 文件(Laravel)

vue.js - Vue3 webcomponents 生产构建问题