Python社区  »  Redis

Likes计数器不会在其他客户端上更新(Laravel+Vue+Redis+Soket.io+Node)

pc sound • 3 周前 • 51 次点击  

我试着制作实时应用程序。当用户单击like按钮时,likes计数器将更新。现在这只对当前用户有效。但是另一个用户没有看到like的数量已经改变(例如,如果它是通过另一个浏览器连接的)。

点击类似按钮后,我在终端服务器上看到消息:

Message received: {"event":"App\\Events\\PostLiked","data":{"result":1,"socket":null},"socket":null}

但是likes计数器只为当前浏览器上的一个用户更新。 我已经做了 两个Vue组件 : 一。喜欢按钮(喜欢帖子)- LikePost.vue公司 2。喜欢计数器标签(显示喜欢计数)- LikePostCount.vue

这是 screenshot

我用 拉维尔5.5+Vue JS 2.5.16

我已安装此库和数据包:

  • 节点
  • redis服务器
  • 快递4.16.3
  • ioredis 3.2.2版
  • 插座.io 2.1.1
  • socket.io-客户端2.2.0

服务器.js

var http = require('http').Server();
var io = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis();
redis.subscribe('news-action');
redis.on('message', function(channel, message) {
 console.log('Message received: ' + message);
 console.log('Channel :' + channel);
 message = JSON.parse(message);
 io.emit(channel + ':' + message.event, message.data);
});
http.listen(3000, function(){
    console.log('Listening on Port: 3000');
});

/资源/资产/js/bootstrap.js

window._ = require('lodash');
window.io = require('socket.io-client');

try {
       require('bootstrap-sass');
} catch (e) {}

window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

window.Vue = require('vue');
window.events = new Vue();

window.flash = function (message) {
    window.events.$emit('flash', message);
};

import Vue from 'vue'
import VueNoty from 'vuejs-noty'

//connects events bus
export const bus = new Vue();
Vue.use(VueNoty)

/资源/资产/js/app.js

require('./bootstrap');

window.Vue = require('vue');

Vue.component('likepost', require('./components/LikePost.vue'));
Vue.component('likepostcount', require('./components/LikePostCount.vue'));

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

/资源/资产/js/components/LikePost.vue

<template> 
        <span>

            <button v-if="isliked" 
                @click.prevent="dislike(post_id)"
                type="button" 
                class="btn btn-block btn-danger btn-xs" 
                name="like-button">
                    <i class="fa fa-heart"></i>
            </button>
            <button v-else
                @click.prevent="like(post_id)" 
                type="button" 
                class="btn btn-block btn-success btn-xs" 
                name="like-button">
                    <i class="fa fa-heart-o">
                        </i>
                </button>

        </span>    
 </template> 

<script>
    import { bus } from '../bootstrap';
    import 'vuejs-noty/dist/vuejs-noty.css'
    export default {
        props: ["post_id", "liked"],

        data: function() {
            return { 
                isliked: '',
            }
        },

        mounted() {
            this.isliked = this.islike ? true : false;
        },
        computed: {
            islike() {
                return this.liked;
            },
        },
        methods: {
            like(post_id) {
            axios
                .post('/blog/posts/like/' + post_id)
                .then(response => { this.isliked = true; 
                      bus.$emit('postliked');
                })
                .catch(response => console.log(response.data));
            },
            dislike(post_id) {
            axios
                .post('/blog/posts/like/' + post_id)
                .then(response => { this.isliked = false; 
                                    bus.$emit('postliked'); 
                })
                .catch(response => console.log(response.data));
            },
        }
    };
</script>

/资源/资产/js/components/LikePostCount.vue

<template> 
        <span>
            <i class="fa fa-heart"></i> {{ likescount }}
        </span>    
 </template> 

<script>
    import { bus } from '../bootstrap';
    import 'vuejs-noty/dist/vuejs-noty.css'
    export default {
        props: {
            post_id: {
                    type: Number,
                    default: () => {}
                }
            },

        data: function() {
            return { 
                likescount: 0,
            }
        },

        created(){
            bus.$on('postliked', (data) => {
               this.updatelikescount(this.post_id); 
            });
        },
        mounted : function() {
            var socket = io('http://localhost:3000');
            socket.on("news-action:App\\Events\\NewEvent", function(data) {
                this.likescount = data.result;

            }.bind(this));

           this.updatelikescount(this.post_id);

        },

        methods: {

            updatelikescount(post_id) {

            axios
                .get('/blog/post/likecount/' + post_id)
                .then(response => {
                    this.likescount = response.data.data[0][0]
                })        
                .catch(response => console.log(response.data));
             },

        }
    };
</script>

/app/Http/Controllers/LikeController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Like;
use App\BlogPost;
use App\Events\PostLiked;

class LikeController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('forbid-banned-user');
    }

    public function likePost($id)
    {
        // here you can check if product exists or is valid or whatever

        $this->handleLike('App\BlogPost', $id);
        $post = BlogPost::find($id);
        $like_count = $post->likes->count();
        event(new PostLiked($like_count));
        return redirect()->back();
    }

    public function handleLike($type, $id)
    {
        $existing_like = Like::withTrashed()->whereLikeableType($type)->whereLikeableId($id)->whereUserId(Auth::id())->first();

        if (is_null($existing_like)) {
            Like::create([
                'user_id'       => Auth::id(),
                'likeable_id'   => $id,
                'likeable_type' => $type,
            ]);
        } else {
            if (is_null($existing_like->deleted_at)) {
                $existing_like->delete();
            } else {
                $existing_like->restore();
            }
        }
    }

}

/app/Events/PostLiked.php

<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class PostLiked implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $result;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->result = $data;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        //return new PrivateChannel('channel-name');
        return ['news-action'];
    }
}

/app/Http/Controllers/BlogPostController.php

<?php

namespace App\Http\Controllers;

use App\BlogPost;
use Illuminate\Support\Facades\Auth;

class BlogPostController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }


    public function postGetLikesCountEvent(BlogPost $post)
    {
        //dd($request);
        $data2[] = [
            $post->likes->count()
        ];

        return Response::json([
            'data' => $data2
        ], 200);

    }
}

/路由/web.php

<?php
//BlogPost - likes - Like button clicked
Route::post('blog/posts/like/{post}', 'LikeController@likePost');
//BlogPost - likes - get likes count
Route::get('blog/post/likecount/{post}', 'BlogPostController@postGetLikesCountEvent');
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/49502
 
51 次点击  
分享到微博
文章 [ 1 ]  |  最新文章 3 周前
pc sound
Reply   •   1 楼
pc sound    11 月前

在的事件名称中有错误 LikePostCount.vue

固定的

socket.on("news-action:App\\Events\\NewEvent"...

socket.on("news-action:App\\Events\\PostLiked"