laravel5.3 vue 实现收藏夹功能实例详解


Posted in Javascript onJanuary 21, 2018

下面通过本文给大家介绍laravel5.3 vue 实现收藏夹功能,具体代码如下所述:

{
 "private": true,
 "scripts": {
 "prod": "gulp --production",
 "dev": "gulp watch"
 },
 "devDependencies": {
 "bootstrap-sass": "^3.3.7",
 "gulp": "^3.9.1",
 "jquery": "^3.1.0",
 "laravel-elixir": "^6.0.0-14",
 "laravel-elixir-vue-2": "^0.2.0",
 "laravel-elixir-webpack-official": "^1.0.2",
 "lodash": "^4.16.2",
 "vue": "^2.0.1",
 "vue-resource": "^1.0.3"
 }
}

​1.0.2 修改 gulpfile.js

将原来的 require('laravel-elixir-vue'); 修改为 require('laravel-elixir-vue-2'); ​

const elixir = require('laravel-elixir');​
require('laravel-elixir-vue-2');​
/*
 |--------------------------------------------------------------------------
 | Elixir Asset Management
 |--------------------------------------------------------------------------
 |
 | Elixir provides a clean, fluent API for defining some basic Gulp tasks
 | for your Laravel application. By default, we are compiling the Sass
 | file for our application, as well as publishing vendor resources.
 |
 */​
elixir(mix => {
 mix.sass('app.scss')
 .webpack('app.js');
});

1.0.3 修改 resource/assets/js/app.js

将原来的 el: 'body' 改为 el: '#app' ​

const app = new Vue({
 el: '#app'
});

1.1 安装npm 模块

(如果之前没有执行此操作) ​

npm  install

laravel5.3 vue 实现收藏夹功能实例详解 

1.2 创建模型及迁移

我们需要一个User模型(laravel附带),一个Post模型和一个Favorite模型以及它们各自的迁移文件。 因为我们之前创建过了 Post 的模型,所以我们只需要创建一个 Favorite 模型即可。 ​

php artisan make:model App\Models\Favorite -m

laravel5.3 vue 实现收藏夹功能实例详解 

​​ 这会创建一个 Favorite

模型以及迁移文件。 ​

1.3 修改 posts 迁移表及 favorites 的 up 方法

给 posts 表在 id 字段后面新增一个 user_id 字段 ​

php artisan make:migration add_userId_to_posts_table --table=posts

修改 database/migrations/2018_01_18_145843_add_userId_to_posts_table.php

public function up()
 {
 Schema::table('posts', function (Blueprint $table) {
  $table->integer('user_id')->unsigned()->after('id');
 });
 }
database/migrations/2018_01_18_142146_create_favorites_table.php ​ 
public function up()
 {
 Schema::create('favorites', function (Blueprint $table) {
  $table->increments('id');
  $table->integer('user_id')->unsigned();
  $table->integer('post_id')->unsigned();
  $table->timestamps();
 });
 }

​ 该 favorites 表包含两列: ​

user_id 被收藏文章的用户ID。

post_id 被收藏的帖子的ID。

​ 然后进行表迁移

php artisan migrate

1.4 用户认证

因为我们之前就已经创建过了,所以这里就不需要重复创建了。

如果你没有创建过用户认证模块,则需要执行 php artisan make:auth ​

2. 完成搜藏夹功能

修改 routes/web.php

2.1 创建路由器

Auth::routes();
Route::post('favorite/{post}', 'ArticleController@favoritePost');
Route::post('unfavorite/{post}', 'ArticleController@unFavoritePost');
Route::get('my_favorites', 'UsersController@myFavorites')->middleware('auth');

2.2 文章和用户之间多对多关系

由于用户可以将许多文章标记为收藏夹,并且一片文章可以被许多用户标记为收藏夹,所以用户与最收藏的文章之间的关系将是多对多的关系。要定义这种关系,请打开 User 模型并添加一个 favorites() ​ app/User.php

注意 post 模型的命名空间是 App\Models\Post 所以注意要头部引入 use App\Models\Post; ​

public function favorites()
 {
 return $this->belongsToMany(Post::class, 'favorites', 'user_id', 'post_id')->withTimeStamps();
 }

​ 第二个参数是数据透视表(收藏夹)的名称。第三个参数是要定义关系(User)的模型的外键名称(user_id),而第四个参数是要加入的模型(Post)的外键名称(post_id)。 ​ 注意到我们链接withTimeStamps()到belongsToMany()。这将允许插入或更新行时,数据透视表上的时间戳(create_at和updated_at)列将受到影响。 ​ ​

2.3 创建文章控制器

因为我们之前创建过了,这里也不需要创建了。

如果你没有创建过,请执行 php artisan make:controller ArticleController ​

2.4 在文章控制器添加 favoritePost 和 unFavoritePost 两个方法

注意要头部要引入 use Illuminate\Support\Facades\Auth; ​

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
use Illuminate\Support\Facades\Auth;
class ArticleController extends Controller
{
 public function index()
 {
 $data = Post::paginate(5);
 return view('home.article.index', compact('data'));
 }
 public function show($id)
 {
 $data = Post::find($id);
 return view('home.article.list', compact('data'));
 }
 public function favoritePost(Post $post)
 {
 Auth::user()->favorites()->attach($post->id);
 return back();
 }
 public function unFavoritePost(Post $post)
 {
 Auth::user()->favorites()->detach($post->id);
 return back();
 }
}

​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();
 }​

2.8 使用组件

引入 Favorite.vue 组件 resources/assets/js/app.js ​

Vue.component('favorite', require('./components/Favorite.vue'));

编译

npm run dev

laravel5.3 vue 实现收藏夹功能实例详解

效果图 ​

laravel5.3 vue 实现收藏夹功能实例详解 

3. 完成 我的收藏夹

3.1 创建用户控制器​

php artisan make:controller UsersController

​ 修改

app/Http/Controllers/UsersController.php ​ 
<?php​
namespace App\Http\Controllers;​
use Illuminate\Http\Request;​
use Illuminate\Support\Facades\Auth;​
class UsersController extends Controller
{
 public function myFavorites()
 {
 $myFavorites = Auth::user()->favorites;
 return view('users.my_favorites', compact('myFavorites'));
 }
}

​ 添加视图文件

// resources/views/users/my_favorites.blade.php
​
extends('layouts.app')
​
@section('content')
<div class="container">
 <div class="row">
 <div class="col-md-8 col-md-offset-2">
  <div class="page-header">
  <h3>My Favorites</h3>
  </div>
  @forelse ($myFavorites as $myFavorite)
  <div class="panel panel-default">
   <div class="panel-heading">
   <a href="/article/{{ $myFavorite->id }}" rel="external nofollow" >
    {{ $myFavorite->title }}
   </a>
   </div>
​
   <div class="panel-body" style="max-height:300px;overflow:hidden;">
   <img src="/uploads/{!! ($myFavorite->cover)[0] !!}" style="max-width:100%;overflow:hidden;" alt="">
   </div>
   @if (Auth::check())
   <div class="panel-footer">
    <favorite
    :post={{ $myFavorite->id }}
    :favorited={{ $myFavorite->favorited() ? 'true' : 'false' }}
    ></favorite>
   </div>
   @endif
  </div>
  @empty
  <p>You have no favorite posts.</p>
  @endforelse
  </div>
 </div>
</div>
@endsection

​ 然后重新向一下根目录 routes/web.php 添加一条路由 ​

Route::get('/', 'ArticleController@index');

laravel5.3 vue 实现收藏夹功能实例详解

最后效果图

总结

以上所述是小编给大家介绍的laravel5.3 vue 实现收藏夹功能,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

Javascript 相关文章推荐
dojo 之基础篇(二)之从服务器读取数据
Mar 24 Javascript
js点击更换背景颜色或图片的实例代码
Jun 25 Javascript
使用jQuery避免鼠标双击的解决方案
Aug 21 Javascript
js中创建对象的几种方式示例介绍
Jan 26 Javascript
JavaScript验证电子邮箱的函数
Aug 22 Javascript
js鼠标滑过图片震动特效的方法
Feb 17 Javascript
Summernote实现图片上传功能的简单方法
Jul 11 Javascript
jQuery Form表单取值的方法
Jan 11 Javascript
详解React Native开源时间日期选择器组件(react-native-datetime)
Sep 13 Javascript
Vue filter介绍及其使用详解
Oct 21 Javascript
angular 内存溢出的问题解决
Jul 12 Javascript
React配置子路由的实现
Jun 03 Javascript
详解node.js中的npm和webpack配置方法
Jan 21 #Javascript
jQuery获取所有父级元素及同级元素及子元素的方法(推荐)
Jan 21 #jQuery
js将当前时间格式化为 年-月-日 时:分:秒的实现代码
Jan 20 #Javascript
Vue cli 引入第三方JS和CSS的常用方法分享
Jan 20 #Javascript
浅谈vue引入css,less遇到的坑和解决方法
Jan 20 #Javascript
vue 引入公共css文件的简单方法(推荐)
Jan 20 #Javascript
基于Vue的ajax公共方法(详解)
Jan 20 #Javascript
You might like
帅气的琦玉老师
2020/03/02 日漫
php数组函数序列之each() - 获取数组当前内部指针所指向元素的键名和键值,并将指针移到下一位
2011/10/31 PHP
PHP警告Cannot use a scalar value as an array的解决方法
2012/01/11 PHP
PHP模拟QQ登录的方法
2015/07/29 PHP
php设计模式之委托模式
2016/02/13 PHP
PHP数据库操作Helper类完整实例
2016/05/11 PHP
javascript document.compatMode兼容性
2010/02/23 Javascript
javascript 密码强度验证规则、打分、验证(给出前端代码,后端代码可根据强度规则翻译)
2010/05/18 Javascript
jQuery 回车事件enter使用示例
2014/02/18 Javascript
JavaScript 实现鼠标拖动元素实例代码
2014/02/24 Javascript
a标签的href与onclick事件的区别详解
2014/11/12 Javascript
JS实现浏览器状态栏文字从右向左弹出效果代码
2015/10/27 Javascript
js实现二级菜单渐隐显示
2015/11/03 Javascript
Bootstrap 附加导航(Affix)插件实例详解
2016/06/01 Javascript
jQuery实现鼠标经过像翻页和描点链接效果
2016/08/08 Javascript
bootstrap组件之按钮式下拉菜单小结
2017/01/19 Javascript
JavaScript 详解预编译原理
2017/01/22 Javascript
js仿拉勾网首页穿墙广告效果
2017/03/08 Javascript
vue-cli axios请求方式及跨域处理问题
2018/03/28 Javascript
AngularJS上传文件的示例代码
2018/11/10 Javascript
Vue中的methods、watch、computed的区别
2018/11/26 Javascript
[41:17]完美世界DOTA2联赛PWL S3 access vs CPG 第二场 12.13
2020/12/17 DOTA
python绘图方法实例入门
2015/05/19 Python
深入理解python中的浅拷贝和深拷贝
2016/05/30 Python
Python实现识别手写数字 简易图片存储管理系统
2018/01/29 Python
python实现求特征选择的信息增益
2018/12/18 Python
华为校园招聘上机笔试题 扑克牌大小(python)
2020/04/22 Python
Django Form 实时从数据库中获取数据的操作方法
2019/07/25 Python
python 普通克里金(Kriging)法的实现
2019/12/19 Python
用html5的canvas和JavaScript创建一个绘图程序的简单实例
2016/07/06 HTML / CSS
国际贸易专业个人职业生涯规划
2014/02/15 职场文书
暑期培训随笔感言
2014/03/10 职场文书
住宅使用说明书
2014/05/09 职场文书
我爱幼儿园演讲稿
2014/09/11 职场文书
会议承办单位欢迎词
2015/09/30 职场文书
2016年最美孝心少年事迹材料
2016/02/26 职场文书