从REST API获取的Vuex渲染数据

vue.js Vue.js

小胖泡芙

2020-03-12

对于这样的组件

<template>
    <div>
        <router-link :to="{name:'section', params: { sectionId: firstSectionId }}">Start</router-link>
    </div>
</template>

<script lang="ts">
    import { mapActions } from "vuex"

    export default {
        mounted() {
            this.getSectionId()
        },
        computed: {
            firstSectionId() {
                return this.$store.state.firstSectionId
            }
        },
        methods: mapActions(["getSectionId"])
    }
</script>

商店:

const store: any = new Vuex.Store({
    state: {
        firstSectionId: null
    },
    // actions,
    // mutations
})

我在一个Web请求getSectionId的行动,并会以异步方式获取数据并调用的突变,将填补firstSectionIdstate在最初的渲染firstSectionIdnull,我得到的是一个必需的参数渲染的过程中丢失的警告router-link

在这里添加不是问题v-if="firstSectionId"但是通常,从服务器获取要显示的数据的方法是什么?目前,我所有的组件都在检查渲染之前存储中是否存在数据,这是正常现象还是有更好的方法等待渲染之前加载数据?

第1140篇《从REST API获取的Vuex渲染数据》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
Sam梅 2020.03.12

根据我的经验,如果您将状态预设为与预期结果相同类型的空值(当然,如果您知道预期的结果),则可以跳过一些检查,例如,如果您有一组项目,则从[]而不是null因为它不会破坏v-for指令,.length检查和类似的数据访问尝试。

但是通常,添加v-if是很正常的事情。文档中一章对此进行了vue-router介绍,并检查属性是否存在正是所建议的内容。它提到的另一种可能的解决方案是在beforeRouteEnterguard 内部获取数据,以确保您始终可以使用已有的数据访问组件。

最终,两种解决方案都是正确的,它们之间的决策更多是关于UX / UI的问题。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android