gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 11:23:59 25 4
gpt4 key购买 nike

我尝试制作实时应用程序。当用户点击“赞”按钮时,“赞”计数器会更新。现在这只适用于当前用户。但是另一个用户看不到点赞数发生了变化(例如,如果它是通过另一个浏览器连接的)。

点击赞按钮后,我在终端服务器消息中看到:

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

但在当前浏览器上,点赞计数器仅针对一个用户进行更新。我制作了两个 Vue 组件:1. 点赞按钮(点赞帖子)- LikePost.vue2. 点赞计数器标签(显示点赞数)- LikePostCount.vue

这是 screenshot

我使用 Laravel 5.5 + Vue JS 2.5.16

我已经安装了这个库和包:

  • Node
  • redis 服务器
  • 表达 4.16.3
  • ioredis 3.2.2
  • socket.io 2.1.1
  • socket.io-客户端 2.2.0

server.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');
});

/resources/assets/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)

/resources/assets/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',
});

/resources/assets/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>

/resources/assets/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);

}
}

/routes/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');

最佳答案

LikePostCount.vue 的事件名称有误

固定

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

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

关于node.js - 喜欢计数器不会在其他客户端上更新(Laravel + Vue + Redis + Soket.io + Node),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54038062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com