laravel 和 vue 上未定义的道具

props undefined on laravel and vue

我需要帮助。我正在使用 laravel、pusher 和 vuejs 处理 real-time 通知。我正在尝试从 blade 模板传递道具中的两个参数,但它们总是 "undefined"

Blade 模板:

<notification :userid="{{$user->IdUsuario}}" :unreads="{{$user->unreadNotifications}}"></notification>

Vuejs:

import NotificationItem from './NotificationItem.vue';
export default {
    props: ['unreads', 'userid'],
    components: {NotificationItem},
    data() {
        return {
            unreadNotifications: this.unreads
        }
    },
    mounted() {
        console.log('Component mounted.');
    Echo.channel('App.User.' + this.userid)
    .listen('.Illuminate\Notifications\Events\BroadcastNotificationCreated', function (e) {
        console.log(e);
        console.log(this.userid);
        let newUnreadNotifications = {
                    data: {
                        IdSalida: e.IdSalida,
                        empleado: e.empleado,
                        status: e.status
                    }
                };
            this.unreads.push(newUnreadNotifications);
    });

    }
}

我不知道我做错了什么:(求救!

如果你想在你的函数中保留组件的上下文,你需要使用Arrow Functions。箭头函数没有自己的作用域,它们继承了父函数的作用域。在您的情况下,在箭头函数中,您仍然会 this 引用该组件。

改变

.listen('.Illuminate\Notifications\Events\BroadcastNotificationCreated', function (e) {

.listen('.Illuminate\Notifications\Events\BroadcastNotificationCreated',(e) => {

你应该定义了变量。

为了让您的代码井井有条,我会将回调放入组件中它自己的方法中并引用该函数。 所以你的代码会变成这样:

mounted() {
    console.log('Component mounted.');
    Echo.channel('App.User.' + this.userid)
       .listen('.Illuminate\Notifications\Events\BroadcastNotificationCreated', this.notificationListener);
},

methods: {
    notificationListener(e) {
        console.log(e);
        console.log(this.userid);
        let newUnreadNotifications = {
            data: {
               IdSalida: e.IdSalida,
               empleado: e.empleado,
               status: e.status
            }
        };
        this.unreads.push(newUnreadNotifications);
    }
}