渲染函数出错:“TypeError:无法读取未定义的属性”在Vue [英] Error in render function: "TypeError: Cannot read property of undefined" in Vue
问题描述
我正在使用Laravel和vue-router。
I am using Laravel and 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'函数返回如下对象:
The 'fetch_board' function returns an object like the following:
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。
When I access the {{ board.category }}
it displays the object correctly; but when I access {{ board.category.title }}
it displays the title, but ALSO gives a TypeError.
如果数据正确加载,为什么我收到此错误?
Why I am getting this error if the data is being loaded correctly?
如何避免/修复此错误?
How can I avoid/fix this error?
推荐答案
您正在看到此错误,因为您正在将board初始化为空数组。当组件在created()钩子之前绑定反应性时,组件尝试评估board.category.title。
You are seeing this error because you are initializing "board" to an empty array. The component tries to evaluate "board.category.title" when it binds the reactivity just prior to the created() hook.
将板设置为空数组,步骤逐步评估可能如下所示:
With board set as an empty array, step by step the evaluation might look like this:
const board = [];
const category = board.category; // undefined
const title = category.title; // TypeError, because category is undefined
如果您初始化数据,则应该停止看到此错误:
You should stop seeing this error if you initialize your data like so:
data() {
return {
board: {
category: {
title: ''
}
}
}
}
这是 Vue生命周期图,其中说明了何时触发created()事件
Here is the Vue lifecycle diagram which illustrates when the created() event is fired
这篇关于渲染函数出错:“TypeError:无法读取未定义的属性”在Vue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!