【发布时间】: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