我有问题。 我使用推杆进行实时通知,当它运行时,它通知我使用noty, 但我也希望它在我的视图中实时显示新通知的数量,类似于facebook。
<span class="label label-warning" v-show="new_count">@{{ new_count }}<!-- get the new notifications --></span>
我该怎么做?
这是我的代码。
nav.js
new Vue({
el: '#nav',
data: {
new_count: 0
},
methods: {
getNewCount: function () {
this.$http.get('cron', function(new_count){
console.log(new_count);
this.new_count = new_count;
}.bind(this));
}
}
});
Cron Job Controller。这种方法每分钟运行一次。
class CronJobController extends Controller
{
public function getIndex()
{
$old_fail_notification = FailNotification::where('seen', 0)->count();
$subjects_with_fail = Grade::where('grade', 'F')->groupBy('subject_id')->orderBy('subject_id', 'ASC')->get();
return response()->json(['new_count' => 2]); //send this to navbar
foreach ($subjects_with_fail as $subject) {
$subject_to_check = Grade::where('grade', 'F')->where('subject_id', $subject->subject_id)->where('reviewed', '0')->get(); //add if grade is IC or D
if (count($subject_to_check) >= 3) {
$failed = new FailNotification();
$failed->message = '[subject-'.$subject->subject_id.'] can now be opened.';
$failed->save();
foreach ($subject_to_check as $subject) {
$subject = Grade::find($subject->id);
$subject->reviewed = 1;
$subject->save();
}
}
}
$fail_notification = FailNotification::all()->count();
//UPDATE NOTIFICATION COUNT HERE REAL TIME USING AJAX
if ($fail_notification > $old_fail_notification) {
$new_notification_count = $fail_notification - $old_fail_notification;
Pusher::trigger('test-channel', 'test-event', [
'name' => 'You have a new',
'message' => 'Notification'
]);
Pusher::trigger('navbar-channel', 'navbar-event', [
'new_notif_count' => $new_notification_count,
]);
return response()->json(['new_count' => $new_notification_count]); //send this to navbar
}
}
}
请告诉我我做错了什么,我该怎么做。
答案 0 :(得分:-1)
this.$http.get()
向服务器发出一个GET请求,该请求不会保持与服务器的连接打开。如果要向网站添加实时功能,则应实现类似socket.io的实现WebSockets的功能。您也可以在后端longpolling
或客户端shortpolling
上进行近实时功能。
答案 1 :(得分:-1)
如果你的php代码是正确的,那么你应该用Vue代码添加订阅者。
首先包括推送脚本(似乎不能作为npm包提供)
<script src="//js.pusher.com/3.0/pusher.min.js"></script>
然后,在vue中,使用您的API_KEY
实例化您的推送器实例,然后停止并倾听
ready () {
const pusher = new Pusher('APP_KEY')
// susbcribe to your channel
const channel = pusher.subscribe('test-channel')
// listen to the event defined on that channel
channel.bind('test-event', data => {
console.log(data.message)
})
}
那应该有用。现在关于你的PHP代码。我不确定trigger
事件是推送器的类方法,在我看到的文档中,触发器被用作实例方法,并且因为您需要传递api密钥和其他身份验证而有意义值,这是在您创建实例时完成的。
require('Pusher.php');
$pusher = new Pusher("APP_KEY", "APP_SECRET", "APP_ID");
$pusher->trigger('test_channel', 'test-event', array('message' => 'hello world') );
因此,请检查您的服务器代码是否正确,但是您确实在客户端上做错了,尝试这些更改并检查是否需要