Laravel使用Vue组件开发进行收藏文章

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_25615395/article/details/79961651

使用Vue组件开发进行收藏文章

前提:

php : 7.1.3
laravel/framework: 5.6.*
vue 2.5.7

先贴一下前端需要的工具package.json问文件,可能存在不需要的

{
  "private": true,
  "scripts": {
    "prod": "gulp --production",
    "dev": "gulp watch"
  },
  "devDependencies": {
    "bootstrap-sass": "^3.3.7",
    "css-loader": "^0.28.11",
    "gulp": "^3.9.1",
    "jquery": "^3.2",
    "laravel-elixir": "^6.0.0-14",
    "laravel-elixir-vue-2": "^0.2.0",
    "laravel-elixir-webpack-official": "^1.0.2",
    "lodash": "^4.17.4",
    "style-loader": "^0.20.3",
    "vue": "^2.5.7",
    "vue-loader": "^10.3.0",
    "vue-resource": "^1.0.3"
  },
  "dependencies": {
    "babel-polyfill": "^6.26.0",
    "vue-image-crop-upload": "^2.2.3"
  }
}

再执行npm insatll

前台的自动构建工具gulp,gulpfile.js

const elixir = require('laravel-elixir');
// var 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 your application as well as publishing vendor resources.
 |
 */

elixir((mix) => {
    mix.sass('app.scss')
       .webpack('app.js');

    mix.version(['js/app.js','css/app.css']);
});

第一步,写收藏的按钮vue,QuestionLike.vue

位置:app\resources\assets\js\components\QuestionLike.vue

<template>
    <div
            class="answer-item-action question-like"
            v-bind:class="{'active':liked}"
            v-html="text"
            v-on:click="like"
    >
        <i class="fa fa-star fa-icon-sm">收藏</i>
    </div>
</template>

<script>
    export default {
        props: ['question'],
        mounted() {
            this.$http.post('/api/question/isLike', {'question': this.question}).then(response => {
                this.liked = response.data.liked;
            })
        },
        data() {
            return {
                liked: false
            }
        },
        methods: {
            like() {
                this.$http.post('/api/question/like', {'question': this.question}).then(response => {
                    this.liked = response.data.liked;
                    console.log("like = " + response.data.liked)
                })
            }
        },
        computed: {
            text() {
                return this.liked ? '<i class="fa fa-star fa-icon-sm"></i>已收藏' : '<i class="fa fa-star fa-icon-sm"></i>收藏';
            }
        }
    }
</script>

第二步,在界面上的使用

@if(Auth::check())
    <question-like question="{{$question->id}}"></question-like>
@else
    <a class="answer-item-action question-like" href="/login">
        <i class="fa fa-star fa-icon-sm"></i>收藏
    </a>
@endif

第三步,将收藏vue组件添加到app.js

位置:app\resources\assets\js\app.js

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

Vue.component('question-like', require('./components/QuestionLike.vue'));

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

这样前台的工作就完成了。

第四步,添加向后台请求的url

Route::middleware('auth:api')->post('/question/isLike', 'QuestionLikeController@isLike');//用户是否收藏了一个问题
Route::middleware('auth:api')->post('/question/like', 'QuestionLikeController@likeThisQuestion');//用户收藏一个问题

第五步,向用户模型中添加方法,检测用户是否收藏了这个问题,用户收藏文章的操作

1. 用户是否收藏了这个问题

    /**
     * 用户是否收藏了这个问题
     *
     * @param $question
     * @return bool
     */
    public function hasLikedThis($question)
    {
        return !!$this->likes()->where('question_id', $question)->count();
    }

2. 用户收藏文章的操作

    /**
     * 用户收藏问题的操作
     *
     * @param $question
     * @return array
     */
    public function likeThis($question)
    {
        return $this->likes()->toggle($question);
    }

第六步,添加向知乎问题收藏控制器收藏的方法

1. 用户是否收藏了这个问题操作

/**
     * 用户是否收藏了这个问题
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function isLike(Request $request)
    {
        $liked = Auth::guard('api')->user()->hasLikedThis($request->get('question'));
        if ($liked) {
            return response()->json(['liked' => true]);
        }
        return response()->json(['liked' => false]);
    }

2. 收藏该问题

/**
     * 收藏该问题
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function likeThisQuestion(Request $request)
    {
        $question = Question::find($request->get('question'));

        $liked = Auth::guard('api')->user()->likeThis($question->id);

        // 如果是取消收藏
        if (count($liked['detached']) > 0) {
            user('api')->decrement('likes_count');
            return response()->json(['liked' => false]);
        }
        user('api')->increment('likes_count');
        $data = ['name' => user('api')->name, 'question' => $question];
        $question->user->notify(new LikeQuestionNotification($data));
        return response()->json(['liked' => true]);
    }
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页