vue.js - Vue2 + Vuex - 不渲染在存储中成功设置的数组
问题描述
我正在尝试渲染 209,579 个选项,但我认为我没有正确使用 Vuex 生命周期 + axios
- 我通过控制台中的 Vuex 在商店状态中看到所有选项。
- 不显示错误
- 选项为空且不渲染状态
cityNames
数组 main.js
正在将商店导出到所有组件
我认为我没有正确应用这个生命周期,我应该在这里使用吸气剂,有人可以为我的生命周期带来秩序吗?
store.js
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
isTrue: true,
cityNames: [],
},
getters:{
getCityNames(state){
return state.cityNames;
}
},
mutations: {
SetCityNames(state, cityNames){
state.cityNames = cityNames
},
actions: {
loadData({commit}){
axios.get('http://localhost:3000/allCities')
.then(function (response) {
commit('SetCityNames', response.data)
}).catch(function (error) {
console.log(error);
});
}
},
});
脚本
export default {
name: "Weather",
methods: {
allCityNames() {
this.$store.dispatch('loadData')
}
},
created() {
this.allCityNames();
}
}
模板
<select>
<option disabled value="">Please select one</option>
<option v-for="cityName in $store.cityNames">{{cityName}}</option>
</select>
谢谢,芽
解决方案
我已经更改了要从计算中执行的代码,但发现错误(终于!)是:maximum stacksize exceeded
,此时我明白 Vue 不允许我将如此庞大的数组(209,579 个项目)渲染到视图中。
第一部分 - 代码更改:
我创建了一个 isLoaded 状态,该状态设置为true
一旦 axios 提交它的响应,
由于 axios 调用的异步性质,我仍然不确定这是否是最好的方法,它可能还没有完成,
commit('SetCityNames', response.data);
并且在调用提交之后,它会调用下一个:commit('changeLoadedState');
所以我补充说:isLoaded: false
添加了一个吸气剂:didItLoad(state){return state.isLoaded}
添加了一个突变:changeLoadedState(state){state.isLoaded = true}
commit('changeLoadedState');
在我的 axios 调用中添加了一个 commit ( ):
loadData({commit}) {
axios.get('http://localhost:3000/allCities')
.then(function (response) {
commit('SetCityNames', response.data);
commit('changeLoadedState');
}).catch(function (error) {
console.log(error);
});
}
在我的组件中,我仍然在方法中调度 axios 调用,因为它首先被调用,并computed
为渲染端添加了一个方法,如下所示:
computed:{
isLoaded(){
return this.$store.getters.didItLoad;
},
renderCities(){
return this.$store.getters.getCityNames;
}
}
在我渲染的模板中,我首先检查我选择的加载状态,然后才填充选项:
<select v-if="isLoaded">
<option disabled value="">Please select one</option>
<option v-for="cityName in renderCities">{{cityName}}</option>
</select>
第 II 部分 - 更改有效负载大小
因此,在直接设置我的代码后,我进入我的节点快递服务器并更改我的路由循环以停止 1000 个项目,并且一切都很好。
在这一点上,我很好奇如果我开始添加零会发生什么情况,所以在 10K 项目时,加载选项需要 1-2 秒,打开下拉列表开始显示由于压力导致的延迟迹象,在 50K 项目时大约需要 5秒打开下拉菜单。
底线
问题不在于数组的大小,Vuex 的工作非常出色,在大约 800 毫秒内获得了 209,579 项数组,其中包括 Express.js 的后端解析(我的整个堆栈都是本地的,因此没有网络延迟)。
我将尝试创建一个自动完成功能,从第二个或第三个字符开始列出。
感谢回复的会员。
推荐阅读
- python - Python : Convert 2D numpy array to pandas series
- text-editor - 如何在 interviewbit 的在线代码编辑器中同时替换所有相同的单词?
- python - 从多个 numpy 数组中删除最小的 p% 数字
- javascript - 我可以用什么代替 Java 中的 Set()?
- javascript - 一种在javascript中循环调整图像大小的方法
- linux - 安装arch后无法上网
- java - 从 C++ 到 Java——什么是 Gradle
- c# - 在 .NET Framework 4 中使用多个环境
- javascript - 制表编辑器选择下拉菜单无法正常工作
- swift - UIActivityViewController 不适用于 WKWebView