javascript – 渲染函数出错:Vue中的“TypeError:无法读取未定义的属性”

我正在使用Laravel和vue-router.

<template>
    <div class="content__inner">
        <div class="forums">

            <!-- Heading -->
            <div class="forums__heading" :style="'border-bottom:2px solid #' + board.category.color">
                <div class="lg-8 md-8 sm-12 column column__first">
                    <h2 class="forums__heading__title">{{ board.title }}</h2>
                </div>
                <div class="lg-1 md-1 sm-1 dtop column text-center">
                    <strong>Replies</strong>
                </div>
                <div class="lg-3 md-3 sm-4 column text-right">
                    <strong>Latest Reply</strong>
                </div>
                <div class="clearfix"></div>
            </div>

            <!-- Content -->
            <div class="forums__content">
                {{ board.category }}
            </div>

        </div>
    </div>
</template>

<script>

    export default {

        data() {
            return {
                board: [],
            }
        },

        created() {
            this.fetch_board(this.$route.params.slug);
        },

        methods: {

            /**
             * Fetch the board.
             *
             * @param string slug   The slug for the board.
             */
            fetch_board(slug)
            {
                this.$http.get('/api/forums/board/' + slug).then((response) => {
                    this.board = response.data;
                });
            },

        }

    };

</script>

‘fetch_board’函数返回如下对象:

board:Object {
    id:5,
    title:"Game Discussion",
    slug:"5-game-discussion",
    description:"General talk about the game.",
    restriction:null,
    category_id:2,
    category:Object {
        id:2
        title:"Community",
        color:"2ECC71",
        created_at:"2017-05-02 07:30:25",
        updated_at:"2017-05-02 07:30:25",
    }
    created_at:"2017-05-02 07:30:25",
    updated_at:"2017-05-02 07:30:25",
}

当我访问{{board.category}}时,它会正确显示对象;但是当我访问{{board.category.title}}时,它显示标题,但是ALSO给出了一个TypeError.

如果数据正确加载,为什么我收到此错误?

如何避免/修复此错误?

最佳答案 您正在看到此错误,因为您正在将“board”初始化为空数组.当组件在created()钩子之前绑定反应时,组件尝试评估“board.category.title”.

将board设置为空数组,逐步评估可能如下所示:

const board = [];

const category = board.category; // undefined

const title = category.title; // TypeError, because category is undefined

如果您初始化数据,则应该停止看到此错误:

data() {
  return {
    board: {
      category: {
        title: ''
      }
    }
  }
}

这是Vue lifecycle diagram,它说明了何时触发created()事件

点赞