首页 > 解决方案 > VueJS 2 应用程序中数据传递的工作流程

问题描述

我对 VueJS 2 很陌生,所以想看看我是否以正确的方式工作。我有一个系统,有人上传一个包含数据的文件,然后将其用于创建图表。所以我向他们显示上传的文件

<tr v-for="file in files.data" :key="file.id">
     //file information
     <td>
         <router-link :to="{ name: file.chart, params: { fileName: file.name }}" 
                tag="a" exact> View Results
         </router-link>
     </td>
</tr> 

所以你可以看到我在表格中有一个链接,它将他们引导到他们上传的文件的图表页面。它包括要加载的文件名的参数。

在图表页面上,我获得了创建方法中的参数。然后我将这些传递给组件以显示图表

<template>
    <div>
       //some information
        <div class="row">
            <div class="col-12" id="parentDiv">
                <barchart :file-name = this.fileName></barchart>
            </div>
        </div>
    </div>
</template>

<script>
    import Barchart from '../charts/Barchart';
    export default {
        components: {
            'barchart': Barchart
        },
        data() {
            return {
                fileName: ''
            }
        },
        created() {
            this.fileName = this.$route.params.fileName;
        }
    }
</script>

最后,我有 Barchart 组件。这就是根据文件上传的数据创建图表的原因。

<script>
    import * as d3 from 'd3';

    export default {
        props: {
            fileName: {
                type: String,
                required: true
            }
        },
        methods: {
            createBarChart() {
              //d3 to create chart using the file that was uploaded
            } 
        },
        created() {
            let vm = this;
            d3.json('storage/' + this.fileName)
                .then(function (data) {
                    vm.createBarChart(data);
                }).catch(function (error) {
                // handle error
            });
        }
    };
</script>

对我来说,似乎有很多数据从一个组件传递到下一个组件。我将它从文件显示组件(显示所有上传的文件)传递到图表页面,然后将其传递给图表组件。

另一个问题是,如果我在图表页面上,并且我刷新页面,那么图表不再具有文件名属性,因此图表不会呈现。我将如何处理这种情况?

任何建议表示赞赏

标签: vue.jsvuejs2vue-component

解决方案


您可能希望查看vuex来管理从父级传递到某个深度嵌套的子级的数据。

在您决定要将文件持久化到嵌套组件中之前,您可能需要考虑这是否是良好的 UX(当用户刷新页面时,他们上传的旧文件仍然被缓存是否有意义?)您可以考虑使用localStorage在本地存储东西,以便在刷新时,数据仍然存在,而无需用户重新输入。


推荐阅读