Vue 2 Laravel 5.3 Eloquent 无法从对象检索数据

Vue 2 Laravel 5.3 Eloquent unable to retrieve data from object

到目前为止,Vue2 对我来说阅读 eloquent 非常好,但除了我难以调试的这一点。

店铺-show.vue

<template>
.....
.....
    <div class="row">
      {{shop.user.id}}
    </div>
.....
.....
</template>

<script>
  export default{
    mounted(){
        this.getShop()
    },
    methods:{
        getShop(){
            var vm = this
        vm.$http.get('/getShop/'+vm.shopId).then((response)=>{
            vm.shop = response.data.data.shop
        })
    },
.....
.....
 }
</script>

ShopController.php

.....
.....
    public function getShop($id)
    {
      $shop = Shop::where('id',$id)->with('user')->firstOrFail();
      $response = [
          'data' => [
              'shop' => $shop
          ]
      ];
      return response()->json($response);
    }
.....
.....

web.php

Route::get('/getShop/{id}', 'ShopController@getShop');

这里,当我在我的模板中呈现 {{shop.user}} 时,它为我提供了完美的用户对象,包括 idname 等信息,但是当我这样做时 {{shop.user.id}}{{shop.user.name}} 它控制台记录错误如下

错误#1

[Vue warn]: Error when rendering component at /Applications/XAMPP/xamppfiles/htdocs/soyegg/resources/assets/js/components/Shop/Shop-show.vue:

错误#2

Uncaught TypeError: Cannot read property 'id' of undefined at Proxy.render (eval at (app.js:335), :46:47) at VueComponent.Vue._render (eval at (app.js:444), :3096:22) at VueComponent.eval (eval at (app.js:444), :2464:21) at Watcher.get (eval at (app.js:444), :1663:27) at new Watcher (eval at (app.js:444), :1655:12) at VueComponent.Vue._mount (eval at (app.js:444), :2463:19) at VueComponent.Vue.$mount (eval at (app.js:444), :6104:15) at VueComponent.Vue.$mount (eval at (app.js:444), :8494:16) at init (eval at (app.js:444), :2777:11) at createComponent (eval at (app.js:444), :4120:9)

以前从来没有过这种情况,很奇怪。请帮忙

当您从 getShop 方法加载 vm.shop 时,这是一个异步方法,在填充之前您不会在 vm.shop 中拥有任何内容,所以最初您会得到这个错误。

为防止此错误,您可以在使用前进行空检查,借助 v-if,如下所示:

<template>
.....
.....
    <div class="row" v-if="shop && shop.user">
      {{shop.user.id}}
    </div>
.....
.....
</template>