无法使用 Vuex 获取所有组件的数据

Cannot use Vuex to fetch data for all components

我试图在 App.vue 中获取数据,然后将值传递给 this.store.data。之后我可以对所有其他组件使用 this.store.data 值。问题是当我点击 link (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 中的获取函数获取数据:

<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

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

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

而不是this.$store.state.senator = this.senatorA,首先你应该像这样执行 Vuex 调度,this.$store.dispatch('storeActionFunction', this.senatorA)

在你的 Vuex 商店文件中,你应该有一个 "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

Getters: https://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

希望对您有所帮助!