【问题标题】:from same axios to different components, VueJS从相同的 axios 到不同的组件,VueJS
【发布时间】: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 中的数据

https://i.stack.imgur.com/J6mlV.png

【问题讨论】:

  • 使用vuex。并将 axios 替换为服务,并在 vuex 商店中使用。
  • 如果这两个组件使用相同的组件,请改用 vuex
  • @Alexander 能否请您检查一下问题,我使用了 vuex,但遇到了一些问题。
  • 我猜,您还没有在主应用程序中以Vue.use(store) 的身份注入您的商店。
  • 你的意思是myComponent 我需要在myComponent 中使用这个Vue.use(store) 吗? @varit05

标签: vue.js vuejs2 vue-component vuex


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    问题是 要解决您遇到的错误,请按照以下步骤操作。

    在初始化 Vue 实例的文件中导入您的商店文件。

    // Assuming your store file is at the same level
    import store from './store';
    

    在你的内部,在你的 Vue 实例中添加 store 对象

    function initApp(appNode) {
        new Vue({
            el: appNode,
            router: Router,
            store // ES6 sytax
        });
    }
    

    到这里,您现在可以从任何组件访问您的商店。

    更新:第二个错误

    不要在组件内部更改数据,而是在商店中更改 mutation 内部的数据,因为您不想在使用相同方法的其他组件中编写相同的登录。

    因此,

    computed: {
        ...mapGetters(["storedData"]),
        anotherFunction() {
           // Function implementation.
        }
    }
    

    在您的突变中设置数据。

    SET_DATA(state, payload) {
        console.log("payload", payload);
        state.storedData = payload;
    }
    

    在 getter 中,您可以执行您在计算属性中执行的操作。

    storedData: function(state) {
        const postData = state.storedData.filter(post => post.userId == 1);
        return postData;
    }
    

    Vuex官方docs

    这是工作的codesandbox

    希望这会有所帮助!

    【讨论】:

    • 首先,感谢您帮助我。真是让我抓狂!好的,我检查了您创建的沙箱并重新创建了我的store.js,就像在沙箱中一样。但我有点困惑(我对此缺乏知识感到抱歉)所以我用新的错误更新了问题中的代码。请检查一下,谢谢。
    • 你不能直接在你的组件内部改变数据,因此如果你需要你的数据来使用reduce,使用mutations 并在其中过滤你的数据而不是在计算属性中进行。您不想在所有使用 fetchData 方法的组件中编写相同的登录信息。像我在代码和框中所做的那样更改计算属性,并在您的商店中添加getters
    • 感谢您的更新,我没有得到的部分是如何将这部分 mapGetters(["storedData"]) 添加到我计算的平均组件中,我更新了代码...因为它说 mapGetters is not defined当我添加它时
    • 您需要从平均组件中删除 storeData,除了 mapGetters(["storedData"]),因为 redux 存储状态也像 vue 数据一样是反应性的。现在您不需要 groupedPricesByRegion 函数,因为它已被移动到存储区。您可以将 averageByRegion 函数移动到 getters 函数。如果它可以帮助您解决您提出的问题,请接受并投票赞成。
    • 如果你想通过mapgetters(['fetchData'])使用另一个函数。请把它当作一个对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    • 2017-03-23
    • 2021-05-20
    • 1970-01-01
    • 2020-07-14
    相关资源
    最近更新 更多