我使用的是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。
如果数据加载正确,为什么会出现此错误?
如何避免/修复此错误?
发布于 2018-08-11 05:43:29
您会看到这个错误,因为您正在将"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: ''
}
}
}
}下面是说明何时触发created()事件的Vue lifecycle diagram
发布于 2020-08-20 17:02:28
官方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选项中声明消息,
会警告你呈现函数正试图访问一个不存在的属性。
https://stackoverflow.com/questions/43737528
复制相似问题