【问题标题】:real-time notification not work laravel 5.4 and vue2实时通知不起作用 laravel 5.4 和 vue2
【发布时间】:2018-01-02 12:52:51
【问题描述】:

我正在尝试在 Laravel 5.4 和 VueJS 2 中制作广播通知 搜索了很多,但没有解决办法。
仅当我刷新页面时才会收到通知
我需要它实时。

navbar.blade.php

     <notification :userid="{{auth()->id()}}" :unreads="{{auth()->user()->unreadNotifications}}"></notification>

Notification.vue

<template>
<li class="dropdown" @click="markasread">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
            <span class="glyphicon glyphicon-globe"></span> Notifications <span
                class="badge alert-danger">{{unreadNotifications.length}}</span>
        </a>

        <ul class="dropdown-menu" role="menu">
            <li>
                <notification-item :key="unread.id" v-for="unread in unreadNotifications" :unread="unread"></notification-item>
            </li>
        </ul>
    </li>
    
</template>

<script>
    import NotificationItem from './NotificationItem.vue';
    export default {
        props: ['unreads', 'userid'],
        components: {NotificationItem},
        data(){
            return {
                unreadNotifications: this.unreads
            }
        },
        methods: {
            markNotificationAsRead() {
                if (this.unreadNotifications.length) {
                    axios.get('/markAsRead');
                }
            }
        },
        mounted() {
            console.log('Component mounted.');
            Echo.private('App.User.' + this.userid)
                .notification((notification) => {
                    console.log(notification);
                    let newUnreadNotifications = {data: {thread: notification.thread, user: notification.user}};
                    this.unreadNotifications.push(newUnreadNotifications);
                });

        }
    }
</script>

NotificationItem.vue

<template>
    <div class="wrap">
        <a :href="threadUrl">
            {{ unread.data.user.name }} commented on {{ unread.data.thread.subject }}
        </a>
    </div>
</template>

<script>
    export default {
        props:['unread'],
        data(){
            return {
                threadUrl:""
            }
        },
        mounted(){
            this.threadUrl="thread/"+ this.unread.data.thread.id
        }

    }
</script>

标题

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>Webdev forum</title>
    <link rel="stylesheet" href="https://bootswatch.com/paper/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.4/css/selectize.min.css">
    <link rel="stylesheet" href="{{asset('css/main.css')}}">
    

    <!-- Scripts -->
    <script>
        window.Laravel = {!! json_encode([
            'csrfToken' => csrf_token(),
        ]) !!};
    </script>
</head>

镀铬控制台

广播.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default Broadcaster
    |--------------------------------------------------------------------------
    |
    | This option controls the default broadcaster that will be used by the
    | framework when an event needs to be broadcast. You may set this to
    | any of the connections defined in the "connections" array below.
    |
    | Supported: "pusher", "redis", "log", "null"
    |
    */

    'default' => "pusher",

    /*
    |--------------------------------------------------------------------------
    | Broadcast Connections
    |--------------------------------------------------------------------------
    |
    | Here you may define all of the broadcast connections that will be used
    | to broadcast events to other systems or over websockets. Samples of
    | each available type of connection are provided inside this array.
    |
    */

    'connections' => [

        'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => 'eu',
                'encrypted' => true
            ],
        ],

        'redis' => [
            'driver' => 'redis',
            'connection' => 'default',
        ],

        'log' => [
            'driver' => 'log',
        ],

        'null' => [
            'driver' => 'null',
        ],

    ],

];

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('example', require('./components/Example.vue'));
Vue.component('notification', require('./components/Notification.vue'));


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

bootstrap.js

window._ = require('lodash');

/**
 * We'll load jQuery and the Bootstrap jQuery plugin which provides support
 * for JavaScript based Bootstrap features such as modals and tabs. This
 * code may be modified to fit the specific needs of your application.
 */

try {
    window.$ = window.jQuery = require('jquery');

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

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require('axios');

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

/**
 * Next we will register the CSRF Token as a common header with Axios so that
 * all outgoing HTTP requests automatically have it attached. This is just
 * a simple convenience so we don't have to attach every token manually.
 */

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

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

import Echo from 'laravel-echo'

window.Pusher = require('pusher-js');

window.Echo = new Echo({
	authEndpoint : 'http://localhost/forum_web/public/broadcasting/auth',

    broadcaster: 'pusher',
    key: '9964dcd35bae49f32d6c',
    cluster: 'eu',
    encrypted: true,
});

.env

APP_NAME=Laravel
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:1R+1MnCFSum8eSSG8NSYeGkEUzABY7W5+wfEqHYMyB0=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=webforum
DB_USERNAME=root
DB_PASSWORD=root

BROADCAST_DRIVER=pusher
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

PUSHER_APP_ID="374057"
PUSHER_APP_KEY="9964dcd35bae49f32d6c"
PUSHER_APP_SECRET="907a71719f0fa029ddf9"

NOCAPTCHA_SECRET=6LfJ3ykUAAAAAAemcVNjirpj1EgEJmRwa6hq321I
NOCAPTCHA_SITEKEY=6LfJ3ykUAAAAAKAh8qP5WJ4L6c3uhubSs26b7s-G

【问题讨论】:

  • 查看 npm 中的错误消息,似乎错误来自您的 v-for 语句,如果您的 v-for"unread as ..." 不是 v-for,请同时查看您的 vue 道具“未读...”是说未读与未读相对吗?
  • data(){ return { unreadNotifications: this.unreads } }
  • 在哪里以及如何初始化 Vue ?另外,请将代码中的 sn-ps 添加到您的问题中,使用屏幕截图很难为您提供帮助。
  • 请粘贴代码,而不是照片
  • 物品unread是否有属性id?

标签: php laravel vue.js vuejs2 vue-component


【解决方案1】:

您应该为每个项目提供一个唯一的key 属性,假设id 是唯一的,在您的Notification.vue 和第10 行:

<notification-item v-for="unread in unreadNotifications" :key="unread.id" :unread="unread"></notification-item>

【讨论】:

  • eluxer.net/code?sesscheck=1&id=227&subid=31477 加载资源失败:服务器响应状态为 404(未找到)53:1 必须有有效as 值 3:1 拒绝执行来自 'f.partnerwork.men/code/code/stat.php' 的脚本,因为它的 MIME 类型 ('text/html') 不可执行,并且启用了严格的 MIME 类型检查。
  • Pusher : 无法从您的 webapp 获取身份验证信息 : 404 这是什么意思???
  • 可能是您对 Pusher 进行了错误的配置。可能是端点?
  • 我修复了这个错误,但仍然不是真正的通知
  • 试试这个:将监听事件方法从mounted更改为created
猜你喜欢
  • 2017-12-30
  • 1970-01-01
  • 1970-01-01
  • 2017-12-13
  • 2017-12-04
  • 2017-07-27
  • 1970-01-01
  • 1970-01-01
  • 2018-01-06
相关资源
最近更新 更多