首页 > 解决方案 > Vue2 + Vuex - 不渲染在存储中成功设置的数组

问题描述

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

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

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>

谢谢,芽

标签: vue.jsvuejs2vuex

解决方案


我已经更改了要从计算中执行的代码,但发现错误(终于!)是: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 的后端解析(我的整个堆栈都是本地的,因此没有网络延迟)。

我将尝试创建一个自动完成功能,从第二个或第三个字符开始列出。

感谢回复的会员。


推荐阅读