laravel5.3 vue 实现收藏夹功能实例详解(3)
2.5 集成 axios 模块
•安装axios
npm install axios --save
•引入axios模块 resource/assets/js/bootstrap.js 在最后加入
import axios from 'axios'; window.axios = axios;
2.6 创建收藏夹组件
// resources/assets/js/components/Favorite.vue
<template>
<span>
<a href="#" rel="external nofollow" rel="external nofollow" v-if="isFavorited" @click.prevent="unFavorite(post)">
<i class="fa fa-heart"></i>
</a>
<a href="#" rel="external nofollow" rel="external nofollow" v-else @click.prevent="favorite(post)">
<i class="fa fa-heart-o"></i>
</a>
</span>
</template>
<script>
export default {
props: ['post', 'favorited'],
data: function() {
return {
isFavorited: '',
}
},
mounted() {
this.isFavorited = this.isFavorite ? true : false;
},
computed: {
isFavorite() {
return this.favorited;
},
},
methods: {
favorite(post) {
axios.post('/favorite/'+post)
.then(response => this.isFavorited = true)
.catch(response => console.log(response.data));
},
unFavorite(post) {
axios.post('/unfavorite/'+post)
.then(response => this.isFavorited = false)
.catch(response => console.log(response.data));
}
}
}
</script>
2.7 视图中引入组件
在视图组件使用之前,我们先引入字体文件 resource/views/layouts/app.blade.php 头部引入字体文件
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
并在 app.blade.php 添加 我的收藏夹 链接
// 加在logout-form之后
<form id="logout-form" action="{{ url('/logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
<a href="{{ url('my_favorites') }}" rel="external nofollow" >我的收藏夹</a>
使用组件
// resources/views/home/article/index.blade.php
if (Auth::check())
<div class="panel-footer">
<favorite
:post={{ $list->id }}
:favorited={{ $list->favorited() ? 'true' : 'false' }}
></favorite>
</div>
endif
然后我们要创建 favorited() 打开 app/Models/Post.php 增加 favorited() 方法
注意要在头部引用命名空间 use App\Models\Favorite; use Illuminate\Support\Facades\Auth;
public function favorited()
{
return (bool) Favorite::where('user_id', Auth::id())
->where('post_id', $this->id)
->first();
}
内容版权声明:除非注明,否则皆为本站原创文章。

