繁体   English   中英

如何使用 Laravel 和 vue js 在数据库中显示单个记录?

[英]How to display a single record in database using Laravel and vue js?

嗨,如何使用 vue js 在数据库上显示单个记录? 我设法显示多个,但我不能显示单行。 这就是我所做的。

<template>
  <div class="container">
    <div class="card-panel z-depth-5 grey lighten-2">
      <blockquote>
        <h3>
          <b>{{tutorial.attributes.title}}</b>
        </h3>
      </blockquote>
      <p class="flow-text">{{tutorial.attributes.content}}</p>
    </div>
  </div>
</template>

<script>
export default {
    name: 'tutorial',
  data: function() {
    return {
        tutorial = {
            id: '',
            content : null,
            title : '',
        },
    };
  },
  mounted() {
    const tutorial_id = this.id;
  },
  props: ['id'],
  methods: {
    get_tutorial: function() {
      //load the tutorials from the api
      axios
        .get('/api/view/' + tutorial_id )
        .then(response => {
          // asign it to data
          this.id = response.data.data.id;
          this.cpntent = response.data.data.content;

        })
        .catch(function(error) {
          // catch errors
          console.log(error);
        });
    }
  }
};
</script>

这是我的 api 路线:(如果我 go 到 '/api/view/1')我成功获取数据我认为我的主要错误是显示它。

Route::get('/view/{id}','TutorialsController@view_tutorial');



 public function view_tutorial($id){ 
      return TutorialResource::collection(Post::all()->where('id',$id));
}

这是我的刀片:

@extends('layouts.main')
@section('styles')
<style>
.card-panel { 
  border-radius:5px;
}
</style>
@stop 
@section('content')

    <div class="app  ">
          <view-tutorial 
          :id="{{ $post->id }}" 
          >
          </view-tutorial>
    </div>

@endsection

@section('scripts')
<script>
<script src="{{mix('js/app.js')}}"></script>
</script>
@ensection

基本上我的模板中有一个 href :href="'/post/' + tutorial.id + '/' + tutorial.slug"当我点击它时,它会将我重定向到我显示帖子内容的页面。 这是我的 web 路线Route::get('/post/{id}/{slug}', 'PostController@read_post'); 当我点击它时,它成功地将我重定向到一个视图,在该视图中我将使用 vue js 显示数据。 在我的模板中,有一个道具会将 ID 发送到组件并使用该 ID 执行一些 axios 获取请求,以便我将在我的数据库中获取特定记录。 我可以使用默认刀片语法显示它,但为了学习我在 vue js 上尝试它。 对不起菜鸟问题。

这是我的错误: 在我的控制台中: SyntaxError: C:\projects\php\blogSite\resources\js\components\View_tutorial.vue: Unexpected token (19:17)

在我的命令提示符下:

SyntaxError: C:\projects\php\blogSite\resources\js\components\View_tutorial.vue: Unexpected token (19:17)

  17 |   data: function() {
  18 |     return {
> 19 |         tutorial = {
     |                  ^
  20 |             id: '',
  21 |             content : null,
  22 |             title : '',

谢谢。 我会感谢所有的帮助。

您可以使用路由 model 绑定。 并从您的数据库中获取特定记录。

阅读文档: https://laravel.com/docs/7.x/routing#route-model-binding

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM