Cannot read property Vue js
Я хочу сделать систему лайков, но в консоли такая ошибка
связанная со строчкой this.totallike = response.data.post.like
Cannot read property 'like' of undefined
Когда я нажимаю, чтобы лайкнуть, то POST http://127.0.0.1:8000/blog/like/undefined 500 (Internal Server Error)
И еще такая Uncaught (in promise) Error: Request failed with status code 500
С Vue.JS не знаком, но срочная нужна реализация на нём. Брал с этого источника
https://www.codechief.org/article/simple-like-system-in-laravel-6-using-vue-js
LikeComponent.vue
<template>
<div class="container">
<p id="success"></p>
<a href="http://"><i @click.prevent="likePost" class="fa fa-thumbs-up" aria-hidden="true"></i>({{ totallike }})</a>
</div>
</template>
<script>
export default {
props:['article'],
data(){
return {
totallike:'',
}
},
methods:{
likePost(){
axios.post('/blog/like/'+this.post,{post:this.post})
.then(response =>{
this.getlike()
$('#success').html(response.data.message)
})
.catch()
},
getlike(){
axios.post('/like',{post:this.post})
.then(response =>{
this.totallike = response.data.post.like
})
}
},
mounted() {
this.getlike()
}
}
</script>
web
Route::any('/blog/article/{slug?}','BlogController@article')->name('article');
Route::post('/like','BlogController@getlike');
Route::post('/blog/like/{id}','BlogController@like');
BlogController
public function getlike(Request $request)
{
$article = Article::find($request->article);
var_dump($article);
return response()->json([
'article'=>$article,
]);
}
public function like(Request $request)
{
$article = Article::find($request->article);
$value = $article->like;
$article->like = $value+1;
$article->save();
return response()->json([
'message'=>'Thanks',
]);
}
article blade
<like-component :post="{{ $article->id }}"></like-component>
Ответы (1 шт):
Вот целостный рабочий пример, включая роутинг, контроллер и компоненты.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
Route::prefix('blog')
->name('blog.')
->group(function () {
Route::get('articles', 'Blog\\BlogController@index')
->name('list');
Route::get('article/{article}', 'Blog\\BlogController@show')
->name('article');
Route::post('article/{article}/like', 'Blog\\BlogController@likeAnArticle')
->name('article.like');
});
BlogController.php
<?php
namespace App\Http\Controllers\Blog;
use App\Http\Controllers\Controller;
use App\Models\Blog\Article;
/**
* Class BlogController
* @package App\Http\Controllers\Blog
*/
class BlogController extends Controller
{
/**
* @return \Illuminate\Http\JsonResponse
*/
public function index()
{
$articles = Article::all();
return response()
->json(compact('articles'));
}
/**
* @param Article $article
* @return \Illuminate\Http\JsonResponse
*/
public function show(Article $article)
{
return response()
->json(compact('article'));
}
/**
* @param Article $article
* @return \Illuminate\Http\JsonResponse
*/
public function likeAnArticle(Article $article)
{
$article->increment('likes', 1);
return response()
->json(compact('article'));
}
}
ArticlesComponent.vue
<template>
<div class="row">
<article-item
:article="article"
:key="`article_${article.id}`"
v-for="article in articles"
v-if="articles.length">
</article-item>
</div>
</template>
<script>
import ArticleComponent from "./ArticleComponent";
export default {
name: "ArticlesComponent",
components: {
'article-item': ArticleComponent
},
props: {
loadUrl: {
type: String,
required: true
}
},
data() {
return {
articles: []
}
},
methods: {
load() {
axios.get(this.loadUrl)
.then(response => response.data)
.then(data => this.articles = data.articles);
}
},
mounted() {
this.load();
}
}
</script>
<style scoped>
</style>
ArticleComponent.vue
<template>
<div class="col-sm-12 col-md-4 col-lg-3">
<h2 v-text="`Article no. ${article.id}`"></h2>
<article-like :article="article"></article-like>
</div>
</template>
<script>
import ArticleLikeComponent from "./ArticleLikeComponent";
export default {
name: "ArticleComponent",
components: {
'article-like': ArticleLikeComponent
},
props: {
article: {
type: Object,
required: true
}
}
}
</script>
<style scoped>
</style>
ArticleLikeComponent.vue
<template>
<span class="like-btn" @click="like" v-html="`<i class='fa fa-thumbs-up'></i> ${article.likes}`"></span>
</template>
<script>
export default {
props: {
article: {
type: Object,
required: true
}
},
data() {
return {
likes: {
count: 0
}
}
},
methods: {
like() {
axios
.post(`/blog/article/${this.article.id}/like`)
.then(r => r.data.article)
.then(article => this.article = article);
}
},
name: "ArticleLikeComponent",
}
</script>
<style scoped lang="scss">
span.like-btn {
cursor: pointer !important;
}
</style>
main.blade.php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Blog Articles</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<!-- Styles -->
<script src="https://use.fontawesome.com/7e87b4c597.js"></script>
</head>
<body>
<div id="solutions" class="container">
<articles-component load-url="{{ route('blog.list') }}"></articles-component>
</div>
<script src="{{ mix('js/app.js') }}"></script>
</body>
</html>
