【问题标题】:Cannot read property 'name' of undefined" when it is defined in the data?在数据中定义时无法读取未定义的属性“名称”?
【发布时间】:2020-01-02 15:20:03
【问题描述】:

这是我执行此操作时看到的数据{{user}}

{ 
   "id":2,
   "name":"Instructor",
   "email":"instructor@gmail.com",
   "email_verified_at":null,
   "created_at":"2019-12-19 10:41:41",
   "updated_at":"2019-12-19 10:41:41",
   "uuid":"6f134dd0-227e-11ea-9d72-035d1b7f6efd",
   "last_name":"Prueba",
   "identification":"",
   "phone":"",
   "address":"",
   "user_type_id":2,
   "ranking":5,
   "user_type":{ 
      "id":2,
      "name":"Instructor"
   }
}

这是发生错误的代码部分

<div class="resume">
    <h3>{{ user.name }}</h3>
        <star-rating v-model="user.ranking" :read-only="true" :star-size="15"
            :show-rating="false"></star-rating>
    <h4>{{ user.user_type.name }}</h4>
</div>

这些是错误

渲染错误:“TypeError:无法读取未定义的属性‘名称’”

TypeError: 无法读取未定义的属性“名称”

错误就在这一行

{{ user.user_type.name }}

这是vue文件的挂载和数据

data() {
    return {
        user: [],
    }
},
mounted() {
    if (this.$page.user) {
        this.user = this.$page.user;
    }
}

这是从控制器发送数据的方式

if (Auth::user()->hasRole(2)) {
$user = Auth::user()->load('userType');
$courses = Course::all();
$locations = Location::all();
$notification = Notification::where('instructor_id', Auth::user()->id)
    ->with('student', 'instructor', 'location', 'course')->get();
if (Auth::user()->rankings()->count() > 0) {
    $user->ranking = Auth::user()->rankings()->avg('ranking');
} else {
    $user->ranking = 5;
}

return Inertia::render('users/show')
    ->with([
        'user' => $user,
        'courses' => $courses,
        'locations' => $locations,
        'notification' => $notification
    ]);
}

为什么会发生这个错误?信息明明在那里,为什么它说它是未定义的?

【问题讨论】:

  • 您能否也展示一下该对象是如何加载到组件中的。你确定不是user.name 抛出错误?
  • @T.Short 我知道这不是另一行,因为错误消息只显示了我上面所说的行,而且我不确定加载的对象是什么意思,你的意思就像数据?
  • 您能否分享您拥有 Vue 组件的整个文件的代码
  • 尝试在您的数据中设置user: null 并添加&lt;div class="resume" v-if="user"&gt;。它解决了你的问题吗?
  • @fabruex 是的,做到了!

标签: vue.js


【解决方案1】:

您可能以异步方式加载数据,因此当模板被挂载时,user 对象还不可用。

为了防止这种情况,只需在您的数据中设置user: null,然后在您的模板中:

&lt;div class="resume" v-if="user"&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 2021-12-06
    • 2022-01-22
    • 2021-11-13
    • 2022-01-14
    • 2022-06-22
    相关资源
    最近更新 更多