gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 22:22:11 29 4
gpt4 key购买 nike

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

Shop-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$3.$mount (eval at (app.js:444), :6104:15) at VueComponent.Vue$3.$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>

关于eloquent - Vue 2 Laravel 5.3 Eloquent 无法从对象检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41994003/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com