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

10 javascript laravel vue.js vue-router

我正在使用 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>
Run Code Online (Sandbox Code Playgroud)

'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",
}
Run Code Online (Sandbox Code Playgroud)

当我访问{{ board.category }}它时,它会正确显示对象;但是当我访问{{ board.category.title }}它时显示标题,但也给出了一个类型错误。

如果数据加载正确,为什么会出现此错误?

如何避免/修复此错误?

Bre*_*ick 6

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

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

const board = [];

const category = board.category; // undefined

const title = category.title; // TypeError, because category is undefined
Run Code Online (Sandbox Code Playgroud)

如果您像这样初始化数据,您应该不会再看到此错误:

data() {
  return {
    board: {
      category: {
        title: ''
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这是Vue 生命周期图,它说明了何时触发 created() 事件