将Laravel中的fetch()与VueJS 3一起使用

将Laravel中的fetch()与VueJS 3一起使用,laravel,vue.js,Laravel,Vue.js,我刚开始用Laravel学习Vue 3,我创建了一个应用程序,其中有: 后模型: <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Post extends Model { use HasFactory; protected $fillable = [

我刚开始用Laravel学习Vue 3,我创建了一个应用程序,其中有:

后模型:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
    protected $fillable = [
        'title', 'content'
    ];
}
routes/api.php
中:

Route::get('/posts', [PostsController::class, 'index']);
这是我的Vue组件:


  • {{post.title}
导出默认值{ 数据(){ 返回{ 员额:[] } }, 创建(){ 取('http://vue-laravel.test/api/posts') 。然后(响应=>{ console.log(响应) }) }, 方法:{ } }
以下是示例数据:

{
    "success": true,
    "message": "List of all Posts",
    "data": [
        {
            "id": 2,
            "title": "Second",
            "content": "Second post",
            "created_at": "2021-01-27T08:08:21.000000Z",
            "updated_at": "2021-01-27T08:08:21.000000Z"
        },
        {
            "id": 1,
            "title": "First",
            "content": "This is my first post",
            "created_at": null,
            "updated_at": null
        }
    ]
}
但是当我
console.log
获取此数据时,我得到以下结果:


使用
console.log(response.data)
,我得到了
未定义的
。有什么建议吗?

应该将
fetch()
(一个
Body
对象)的解析结果转换为JSON,并使用以下方法:

fetch('http://vue-laravel.test/api/posts')
.then(resp=>resp.json())
.then(json=>this.posts=json.data)

应将
fetch()
(一个
Body
对象)的解析结果转换为JSON,具体如下:

fetch('http://vue-laravel.test/api/posts')
.then(resp=>resp.json())
.then(json=>this.posts=json.data)

是的,我通过json.posts获得它。。5分钟前,我尝试了:async getPosts(){const response=await fetch(')const responseData=await response.json()console.log(responseData.posts)this.posts=responseData.posts},我再次成功了。是的,我用json.posts获得了它。。5分钟前,我尝试了:async getPosts(){const response=await fetch(')const responseData=await response.json()console.log(responseData.posts)this.posts=responseData.posts},再次获得成功
{
    "success": true,
    "message": "List of all Posts",
    "data": [
        {
            "id": 2,
            "title": "Second",
            "content": "Second post",
            "created_at": "2021-01-27T08:08:21.000000Z",
            "updated_at": "2021-01-27T08:08:21.000000Z"
        },
        {
            "id": 1,
            "title": "First",
            "content": "This is my first post",
            "created_at": null,
            "updated_at": null
        }
    ]
}