【问题标题】:Cannot use Vuex to fetch data for all components无法使用 Vuex 获取所有组件的数据
【发布时间】:2019-02-14 00:45:05
【问题描述】:

我尝试在 App.vue 中获取数据,然后将值传递给 this.store.data。之后,我可以将 this.store.data 值用于所有其他组件。问题是当我点击链接(router-link)时,组件内的函数在应用程序中获取数据之前运行。无论如何我可以解决这个问题吗?如何获取数据并用于所有其他组件?

这里是store.js的代码:

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
      senator: [],
  },
  mutations: {},
  actions: {}
});

这里是App.vue中获取数据的代码:

<script>
import Header from "./components/Header";
import Footer from "./components/Footer";
export default {
    components: {Header, Footer},
    data(){
        return {
            senatorA: [],
        }
    },
    created: function(){
        this.getData();
    },
    methods: {
        getData() {
            let pathSenate = 'senate';
            let url = '';
            let currentPage = window.location.href;
            if (currentPage.includes(pathSenate)) {
                url = 'https://api.myjson.com/bins/1eja30';

            } else {
                url = 'https://api.myjson.com/bins/j83do';
            }
            fetch(url)
                .then(response => response.json())
                .then((jsonData) => {
                    let data = jsonData;
                    this.senatorA = data.results[0].members;
                    this.senatorA.forEach(mem => {
                        mem.fullname = (mem.first_name + ' ' + mem.middle_name + ' ' + mem.last_name).replace(null, '');
                    });
                    this.$store.state.senator = this.senatorA;
                    console.log(this.$store.state.senator)
                });
        },
    }
}

这是组件中的代码,用于从 App.vue 中的 fetch 函数中获取数据:

<script>
import DataTable from './DataTable'
export default {
    name: "FilterData",
    components: {DataTable},
    data () {
        return {
            senatorF: this.$store.state.senator,
            checkarr: [],
            selectarr: '',
            statearr: [],
            searchName: '',
            tempt: [],
        }
    },
    created: function(){
        this.getStates();
    },
    computed: {
        displayParty() {
            if (this.checkarr.length == 0 && this.selectarr == '') {
                return this.searchData(this.senatorF);
            } else if (this.checkarr.length != 0 && this.selectarr == '') {
                this.tempt = this.senatorF.filter(j => this.checkarr.includes(j.party));
                return this.searchData(this.tempt);
            } else if (this.selectarr != '' && this.checkarr.length == 0) {
                this.tempt = this.senatorF.filter(j => this.selectarr.includes(j.state));
                return this.searchData(this.tempt)
            } else {
                let  memFilter= [];
                for (let j = 0; j < this.senatorF.length; j++) {
                    for (let i = 0; i < this.checkarr.length; i++) {
                        if (this.senatorF[j].party == this.checkarr[i] && this.senatorF[j].state == this.selectarr) {
                            memFilter.push(this.senatorF[j]);
                        }
                    }
                }
                return this.searchData(memFilter);
            }
        },
    },
    methods: {
        getStates: function () {
            console.log(this.senatorF)
            this.senatorF.forEach(mem => {
                if (!this.statearr.includes(mem.state)) {
                    this.statearr.push(mem.state);
                    console.log('addrow')
                }
            });
        },
        searchData: function(array){
            return array.filter(mem => mem.fullname.toLowerCase().includes(this.searchName.toLowerCase()) || mem.votes_with_party_pct.toString().includes(this.searchName.toLowerCase()))
        }
    },
};

这是控制台中的结果: console result show the function in component run before the fetching data in App.vue

【问题讨论】:

  • 欢迎来到 StackOverflow。请查看如何发布问题的帮助部分:stackoverflow.com/help/how-to-ask。这将大大增加您获得相关答案的机会。
  • 请提供你的商店vuex的代码
  • 我只是在我的帖子中添加了来自 store vuex 的代码

标签: vue.js vuejs2 vue-component vuex vue-cli


【解决方案1】:

你已经取得了一些不错的进展。接下来的步骤是遵循 Vuex 中的正确流程来“更新”您的商店。在您的App.vue 中,您拥有最终执行fetch()getData() 方法,并且您尝试使用this.$store.state.senator = this.senatorA 设置您的商店数据。这是不正确的。你应该遵循 Vuex 的单向数据流结构。

您正在尝试直接更改状态,而无需先将更改提交给突变,这会直接影响状态。我知道这可能看起来很多,甚至 Evan You(Vue 的创建者)也表示他想简化。

除了this.$store.state.senator = this.senatorA,你首先应该像this.$store.dispatch('storeActionFunction', this.senatorA)那样执行一个Vuex调度。

在你的 Vuex Store 文件中,你应该有一个“Action”(函数),然后调用 commit。您的提交可能类似于commit('SET_SENATAOR_SOMETHING', data)data 将代表您通过调度传递的this.senatorA

commit() 有 2 个参数...您要定位的 Mutation 名称和您要传递的数据。然后你会在你的 Vuex 商店中有一个部分,你可以在其中指定你的 Mutations。然后,一个名为 'SET_SENATAOR_SOMETHING' 的突变会接收传入的数据并执行类似... state.senator = data 的操作。

轰隆隆。完毕。看起来很多,但它就是这样工作的。如果您想查看一些示例文件,我在下面链接了一个项目,但我的项目比您想要做的抽象程度更高。

状态https://github.com/rebz/vue-meetup-interfaces/blob/master/resources/js/store/modules/people/state.js

派送https://github.com/rebz/vue-meetup-interfaces/blob/master/resources/js/views/people/layouts/layout.vue

行动https://github.com/rebz/vue-meetup-interfaces/blob/master/resources/js/store/modules/people/actions.js

变异https://github.com/rebz/vue-meetup-interfaces/blob/master/resources/js/store/modules/people/mutations.js

Gettershttps://github.com/rebz/vue-meetup-interfaces/blob/master/resources/js/store/modules/people/getters.js

使用{ mapGetters }(非必需)访问数据:https://github.com/rebz/vue-meetup-interfaces/blob/master/resources/js/views/people/index.vue

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 2017-03-12
    • 2022-08-14
    • 2020-04-13
    • 2020-12-08
    相关资源
    最近更新 更多