Обновление файла vue при внесении изменений - Laravel Echo Pusher Notifications - PullRequest
0 голосов
/ 05 марта 2019

Итак, в течение последних нескольких дней я пытался автоматически перезагрузить этот шаблон, когда что-то новое произошло. То есть, когда «Уведомления» были изменены, либо добавлена ​​новая запись, либо уведомление было помечено как прочитанное.

Я использую выпадающий список, чтобы показать результаты, и сейчас мне нужно перезагрузить всю страницу, когда что-то происходит. Что не очень хорошо для современного приложения.

PS. Я совершенно новичок в Vue, поскольку эта интеграция с уведомлениями Laravel.

Это мой файл .vue (и вы можете видеть, что я сам несколько раз пытался безуспешно)

<template>
    <li class="dropdown">
        <a href="#" class="dropdown-toggle icons" data-toggle="dropdown" role="button"
           aria-haspopup="true" aria-expanded="false">
            <span class="badge badge-dark badge-corner fs-11">{{ notifications.length }}</span>
            <i class="fas fa-bell fs-15" style="color: #444;"></i>
        </a>
        <ul
            class="dropdown-menu dropdown-menu-right notify-drop">
            <li>
                <div class="notify-drop-title">
                    <div class="row">
                        <div class="col-10">Notifikationer (<b>{{ notifications.length }}</b>)</div>
                        <div class="col-2 text-right">
                            <button class="rIcon allRead"
                                    data-tooltip="tooltip"
                                    data-placement="bottom"
                                    title="Markera alla som lästa"><i
                                class="fa fa-bullseye fs-12"></i>
                            </button>
                        </div>
                    </div>
                </div>
                <!-- end notify title -->
                <!-- notify content -->
                <div class="drop-content">
                    <div class="thisItem" v-for="notification in notifications" :key="notification.id">
                        <div class="row pl-10">
                            <div class="col-1">
                                <div
                                    v-if="notification.data.type === 'friend' || notification.data.type === 'friendAccept'">
                                    <i class="fas fa-heart fs-25 primary mt-5"></i>
                                </div>
                                <div v-if="notification.data.type === 'friendDeny'">
                                    <i class="fas fa-heart-broken fs-25 primary mt-5"></i>
                                </div>
                            </div>
                            <div class="col-10 ml-5">
                                <button class="float-right rIcon mr-1" data-toggle="tooltip"
                                        data-placement="top" title="Markera som läst"
                                        v-on:click="MarkAsRead(notification)">
                                    <i class="fa fa-bullseye fs-12"></i>
                                </button>

                                <a class="fs-14 m-0" style="text-transform: none;" :href="'/profile/' + notification.data.accessurl">{{
                                    notification.data.fromuser }}</a>
                                <span class="fs-12 m-0 text-muted">{{ notification.data.message }}</span>

                                <div v-if="notification.data.type === 'friend'">
                                    <button type="button" class="btn btn-primary btn-sm"
                                            v-on:click="AcceptFriend(notification)">Acceptera
                                    </button>
                                    <button type="button" class="btn btn-primary btn-sm"
                                            v-on:click="DenyFriend(notification)">Neka
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="notify-drop-footer text-center">
                    <a href=""><i class="fa fa-eye"></i> Visa Alla</a>
                </div>
            </li>
        </ul>
    </li>
</template>

<script>
    export default {
        props: ['notifications'],
        methods: {
            MarkAsRead: function (notification) {
                const data = {
                    id: notification.id
                };
                const self = notification;
                axios.post('/notification/read', data).then(response => {
                    //self.id = '';
                    //self.$forceUpdate();
                    //self.notification += 1;
                    //self.setState({notification: response.data});
                    //self.data.fromuser = '';
                    //self.data.message = response.data;
                    //this.notifications.splice(notification,1);
                    console.log(response.data);
                });
            },
            AcceptFriend: function (notification) {
                const data = {
                    id: notification.id,
                    friendid: notification.data.itemid,
                    fromuserid: notification.data.fromuserid
                };

                axios.post('/notification/acceptFriend', data).then(response => {
                    console.log(response.data);
                });

                axios.post('/notification/read', data).then(response => {
                    console.log(response.data);
                });
            },
            DenyFriend: function (notification) {
                const data = {
                    id: notification.id,
                    friendid: notification.data.itemid,
                    fromuserid: notification.data.fromuserid
                };

                axios.post('/notification/denyFriend', data).then(response => {
                    console.log(response.data);
                });

                axios.post('/notification/read', data).then(response => {
                    console.log(response.data);
                });
            }
        }
    }
</script>

My app.js

Vue.component('notification', require('./components/Notification.vue'));

const app = new Vue({
    el: '#app',
    data: {
        notifications: ''
    },
    created() {
        axios.post('/notification/get').then(response => {
            this.notifications = response.data;
        });

        var userId = $('meta[name="userId"]').attr('content');
        Echo.private('App.User.' + userId).notification((notification) => {
            this.notifications.push(notification);
        });
    },
    computed: {
        notifications: function () {
            return this
        }
    }
});

Заранее благодарю всех, кто может помочь мне решить эту проблему!

1 Ответ

0 голосов
/ 05 марта 2019

Насколько я понимаю, вы хотите отображать несколько уведомлений каждый раз, когда вы получаете новые данные уведомлений?

В таком случае вы можете использовать props.если вы добавите props в компонент уведомления, компонент уведомления будет перерисовываться всякий раз, когда props изменится

пример

<notification :notifications='notifications'><notification>

https://vuejs.org/v2/guide/components-props.html

...