gpt4 book ai didi

vue.js - Vue2 + Vuex - 不渲染在商店中成功设置的数组

转载 作者:搜寻专家 更新时间:2023-10-30 22:37:36 25 4
gpt4 key购买 nike

我正在尝试渲染 209,579 个选项,但我认为我没有正确使用 Vuex 生命周期 + axios

  • 我在控制台中看到所有通过 Vuex 设置在商店状态的选项。
  • 没有显示错误
  • 选项为空且未呈现状态 cityNamesarray
  • main.js 正在将存储导出到所有组件

我认为我没有正确应用这个生命周期,我应该在这里使用 getter,有人可以给我的生命周期带来秩序吗?

商店.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>

谢谢,花蕾

最佳答案

我已经更改了我的代码以从计算中执行,只是为了找出错误(终于!)这是:超出最大堆栈大小,此时我明白 Vue 不允许我将如此庞大的数组(209,579 项)渲染到 View 中。

第一部分 - 代码更改:

我创建了一个 isLoaded 状态,一旦 axios 提交它的响应,它就设置为 true

I'm still not sure if this is the best method due to the async nature of axios's call, it could have not finished with commit('SetCityNames', response.data); and right after invoking the commit, it would invoke the next : commit('changeLoadedState');

所以我添加到状态:isLoaded: false

添加了一个 getter:didItLoad(state){return state.isLoaded}

添加了一个突变:changeLoadedState(state){state.isLoaded = true}

在我的 axios 操作调用中添加了一个提交 (commit('changeLoadedState');):

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>

第二部分 - 更改负载大小

所以在直接设置我的代码之后,我进入了我的 node express 服务器并将我的路由循环更改为在 1000 个项目处停止,并且一切正常。

在这一点上,我很好奇如果我开始添加零会发生什么,所以在 10K 项时,需要 1-2 秒来加载选项,打开下拉列表开始显示由于压力导致的延迟迹象,在 50K 项时它打开下拉菜单大约需要 5 秒钟。

底线

问题不在于数组的大小,Vuex 工作得惊人,在大约 800 毫秒内获得了 209,579 项数组,其中包括 Express.js 的后端解析(我的整个堆栈都是本地的,因此没有网络延迟)。

我将尝试创建一个从第 2 个或第 3 个字符开始列出的自动完成。

感谢回复成员(member)。

关于vue.js - Vue2 + Vuex - 不渲染在商店中成功设置的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50083946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com