【问题标题】:Cannot display data from axios response in vue component无法在 vue 组件中显示来自 axios 响应的数据
【发布时间】:2019-08-12 17:46:54
【问题描述】:

使用 axios 检索的数据未显示在 vue 上,尽管在 vue-dev 工具中存在数据。另外我收到错误:[Vue 警告]:渲染错误:“TypeError:无法读取 null 的属性 'logbook_id'” 和 TypeError:无法读取 null 的属性 'logbook_id'。 Laravel 中的新功能。谢谢。

Data retrieved from response

Vue 组件

<template>
<div class="container">
    <h1 v-for="log in logbook" v-bind:key="log.logbook_id" > {{ log.title }} 
</h1>
</div> 
</template>

<script>
export default {
    data(){
        return{
            logbook:{},
        }
    },
    methods:{
        fetchLog(){
            const url = `/api/logbook/${this.$route.params.id}`;
            axios.get(url).then(response => this.logbook = response.data);
        },
    },
    mounted() {
        console.log('Component mounted.');
        this.fetchLog();
    }
}

控制器

    public function show($id)
{
    $log = logbook::where(['logbook_id' => $id])
    ->first();
    return response($log);
}

【问题讨论】:

  • 你没有json_encode()吗?
  • @vivek_23 你的意思是这样吗?返回 json_encode($log);
  • 是的,json_encode($log);。这会将 JSON 格式的数据发送到客户端。
  • 另外,response =&gt; this.logbook = response.data 应该是 (response) =&gt; { this.logbook = response.data}) 吗?请注意,如果您使用的是.data,则需要确保在从服务器向 vue 发送响应时添加该密钥。
  • 两个都试过了,可惜还是一样。我认为主要错误是“无法读取 null 的属性'logbook_id'”。我不确定那是什么意思。 @vivek_23

标签: php laravel vue.js axios


【解决方案1】:

您只能返回一个日志对象,而不是一个数组。如果您返回一个数组,您当前的语法将起作用。 v-for 的目的通常是有一个项目列表,但由于你只有一个项目,所以没有一个列表的目的。

【讨论】:

    猜你喜欢
    • 2019-06-19
    • 2023-02-15
    • 2019-12-11
    • 2019-06-08
    • 2020-04-08
    • 1970-01-01
    • 2017-06-01
    • 2020-01-07
    • 1970-01-01
    相关资源
    最近更新 更多