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

时间:2017-05-02 12:09:18

标签: 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>

'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 }}时,它会显示标题,但是也提供了一个TypeError。

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

如何避免/修复此错误?

2 个答案:

答案 0 :(得分:3)

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

将板设置为空数组,逐步评估可能像这样:

if( response == 10 ){
    swal({
      type: 'success',
      title: 'YOUR BALANCED BOX IS FULL',
      text: 'Youve added the recommended amount of items for your plan!',
      allowOutsideClick: false,
      showCancelButton: true,
      cancelButtonText: "Modify Selection",
      cancelButtonColor: '#d33',
      showConfirmButton: true,
      confirmButtonColor: '#61ce70',
      confirmButtonText: "Proceed To Cart",
    }).then((result) => {
        if (result.value) {
            window.location = "/basket/";
        }
    }) 
}

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

const board = [];

const category = board.category; // undefined

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

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

答案 1 :(得分:1)

此错误在官方Vue documentation中进行了解释:

由于Vue不允许动态添加根级反应性属性,因此您必须通过预先声明所有根级反应性数据属性(即使值为空)来初始化Vue实例:

var vm = new Vue({
  data: {
    // declare message with an empty value
    message: ''
  },
  template: '<div>{{ message }}</div>'
})
// set `message` later
vm.message = 'Hello!'

如果您未在data选项中声明消息,Vue会警告您渲染功能正在尝试访问不存在的属性。