【问题标题】:props undefined on laravel and vue在 laravel 和 vue 上未定义的道具
【发布时间】:2020-04-13 04:37:30
【问题描述】:

我需要帮助。我正在使用 laravel、pusher 和 vuejs 开发实时通知。我试图从刀片模板中传递两个参数,但它们总是“未定义”

刀片模板:

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

    }
}

我不知道我做错了什么:(帮助!

【问题讨论】:

  • 你试过在没有:的情况下使用useridunreads吗?

标签: laravel vue.js pusher


【解决方案1】:

如果你想在你的函数中保留组件的上下文,你需要使用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);
    }
}

【讨论】:

    猜你喜欢
    • 2017-04-17
    • 2018-04-10
    • 1970-01-01
    • 2018-01-27
    • 2021-02-12
    • 2020-08-03
    • 2021-06-06
    • 2021-12-12
    相关资源
    最近更新 更多