【问题标题】:Can't get data in laravel vuelaravel vue 无法获取数据
【发布时间】:2019-01-18 06:28:54
【问题描述】:

我尝试通过 slug 显示我的帖子的详细信息,但数据不会呈现。我只是得到我的导航栏和白页,

代码

controller

public function single($slug)
    {
        $post = Post::where('slug', $slug)->first();
        return response()->json([
            "post" => $post
        ], 200);
    }

single.vue 我在哪里显示我的单个帖子数据

<template>
    <div class="post-view" v-if="post">
        <div class="user-img">
            <img src="...." alt="">
        </div>
        <div class="post-info">
            <table class="table">
                <tr>
                    <th>ID</th>
                    <td>{{ post.id }}</td>
                </tr>
                <tr>
                    <th>Title</th>
                    <td>{{ post.title }}</td>
                </tr>
                <tr>
                    <th>Body</th>
                    <td>{{ post.body }}</td>
                </tr>
            </table>
            <router-link to="/blog">Back to all post</router-link>
        </div>
    </div>
</template>

<script>
    export default {
        created() {
            if (this.posts.length) {
                this.project = this.posts.find((post) => post.slug == this.$route.params.slug);
            } else {
                axios.get(`/api/posts/${this.$route.params.slug}`)
                    .then((response) => {
                        this.post = response.data.post
                    });
            }
        },
        data() {
            return {
                post: null
            };
        },
        computed: {
            currentUser() {
                return this.$store.getters.currentUser;
            },
            posts() {
                return this.$store.getters.posts;
            }
        }
    }
</script>

vuex store.js

state: {
        posts: []
    },
getters: {
        posts(state) {
            return state.posts;
        }
    },
mutations: {
        updatePosts(state, payload) {
            state.posts = payload;
        }
    },
actions: {
        getPosts(context) {
            axios.get('/api/posts')
            .then((response) => {
                context.commit('updatePosts', response.data.posts);
            })
        }
    }

问题

  1. 为什么我无法获取我的帖子数据?我的代码有什么错误吗?

.................................................. ..................................................... ..................................................... ....................

【问题讨论】:

  • @BennettDams 非常感谢它现在正在工作

标签: laravel vue.js vue-router


【解决方案1】:

您正在调用/api/posts/${this.$route.params.slug},它(按照 REST 约定)返回一个帖子对象。

在设置您的帖子 (this.post = response.data.post) 时,您应该使用 response.data(不带 .post

【讨论】:

    猜你喜欢
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 2019-08-12
    • 1970-01-01
    • 2020-07-13
    • 2020-06-03
    • 2020-12-14
    相关资源
    最近更新 更多