" comment.user.name"未定义错误 - Laravel和VueJS

时间:2017-12-10 14:13:06

标签: javascript laravel-5 eloquent vuejs2 vuex

我使用Laravel 5,VueJS 2和Vuex构建了一个评论系统。我可以检索所有注释,并且当我加载页面时,comment.user.username工作正常。 但是当我发布一条新评论时,我在我的控制台中收到了这个错误:

[Vue warn]: Error in render function: "TypeError: _vm.comment.user is undefined"

当我用comment.user_id替换comment.user.name时,我发布了它的作品。 comment.created_at也有效。 comment.user.name在我重新加载页面时显示用户名但是当我发布时,我收到未定义的错误

定义了注释和用户模型关系。 请问,我该如何解决此错误?

1 个答案:

答案 0 :(得分:0)

我的评论表 enter image description here

我的评论.vue

<template>

<div class="ui comments innerAllWithoutTop">
    <div class="ui inverted active dimmer" v-if="loading">
        <div class="ui text loader">Chargement des commentaires...</div>
    </div>
  <h4 class="ui dividing header">Les commentaires</h4>
  <comment :comment="comment" v-for="comment in comments" :key="id"></comment>
  <comment-form :id="id" :model="model"></comment-form>
</div>

</template>
<script type="text/babel">
import axios from 'axios'
import Comment from './comments/Comment.vue'
import CommentForm from './comments/Form.vue'
import store from '../store/Store'


export default {
  data () {
    return {
        loading: true,
    }
  },
  computed: {
    comments: {
        get: function () {
            return store.state.comments
        },
        set: function (comments) {
            store.commit('ADD_COMMENTS', comments)
        }
    }
  },
  components: { Comment, CommentForm },
  props: {
    id: Number,
    model: String
  },
  methods: {
    getComments () {
      axios.get('/comments', {params: {
        type: this.model, id: this.id
      }}).then((response) => {
        this.comments = response.data
      }).then(() => {
        this.loading = false
      });
    }
  },
  mounted () {
    this.getComments();
  }
}
</script>

我的评论.vue

<template>
  <div class="comment">
      <a class="avatar">
        <img :src="comment.user.profile.photo">
      </a>
      <div class="content">
        <a class="author">{{ comment.user.username }}</a>
        <div class="metadata">
          <span class="date">{{ comment.created_at }}</span>
        </div>
        <div class="text">
          {{ comment.content }}
        </div>
        <div class="actions">
          <a class="reply">Répondre</a>
        </div>
      </div>
      <div class="comments" v-if="comment.reply == 0">
      <comment :comment="reply" v-for="reply in comment.replies" :key="reply.id"></comment>
      <!--<comment-form :model="comment.commentable_type" :id="comment.commentable_id" :reply="comment.id" v-if="comment.reply == 0"></comment-form>-->
      </div>
  </div>
</template>

<script>
import CommentForm from './Form.vue'

  export default {
    name: 'comment',
    components: { CommentForm },
    props: {
      comment: Object
    }
  }
</script>

评论有效,用户名有效,但当我发表评论时,我在控制台

中获得未定义的comment.user