【问题标题】:Remove class for another user vue.js删除另一个用户 vue.js 的类
【发布时间】:2018-07-30 02:18:05
【问题描述】:

我有聊天消息系统。
我有代码:

<template>
<li :class="className">
     {{ message }}
</li>
</template>

<script>
export default {
    props: [
        'message',
        'user',
        'time',
        'seen',
    ],
    computed: {
        className() {
            return this.seen;
        }
    },
    mounted() {
        console.log('Component mounted.')
    }
}
</script>

App.js:

data:{
        message: '',
        convId: 1,
        chat: {
            message: [],
            user: [],
            time: [],
            seen: [],
        },
        typing: '',
    },    
    
    ....
    
    watch: {
    message() {
        Echo.private('chat')
            .whisper('typing', {
                name: this.message
            });
    }
},
methods: {
    send(){
        if(this.message.length != 0 && this.message.length <= 4000) {
            this.chat.message.push(this.message);
            this.chat.user.push('you');
            this.chat.time.push(this.getTime());
            this.chat.seen.push('unread'). //set class unread message for user
            axios.post('/sendMessage', {
                message: this.message,
                //lastName: 'Flintstone'
              })
              .then(response => {
                console.log(response);
                this.message = '';
              })
              .catch(error => {
                console.log(error);
              });
        }
    },
    seenMessage() {
    axios.post('/setMessagesSeen/' + this.convId) //this request mark messages in chat all readed for auhenticated user
            .then( response => { this.chat.seen.push(''); //remove unread class }) 
            .catch( response => { console.log(response) } )
    },
    getTime() {
        let time = new Date();
        return time.getHours() + ':' + time.getMinutes();
    }
},

mounted() {
    Echo.private('chat')
        .listen('ChatEvent', (e) => {
            this.chat.message.push(e.message);
            this.chat.user.push(e.user);
            this.chat.time.push(this.getTime());
            this.chat.seen.push('unread'). //set class unread message for user
            console.log(e);
        })
        .listenForWhisper('typing', (e) => {
            if(e.name != '')
                this.typing = 'typing..';
            else
                this.typing = null;
        });
}

我的chat.blade.php:

            <message v-for="value,index in chat.message" 
                :key=value.index 
                :user=chat.user[index]
                :message="chat.message[index]"
                :time="chat.time[index]"
                :seen="chat.seen[index]"
            >
            </message>
    <div class="form-group">
                <textarea maxlength="4000" cols="80" rows="3" class="message-input form-control" v-model='message' v-on:click="seenMessage"></textarea>
              </div>
              <div class="form-group">
                  <button type="button" class="btn btn-lg btn-primary" v-on:click="send">Send message</button>
              </div>

我看到的函数:

public function setMessagesSeen(Conversation $conversation) {
    $user = User::find(Auth::id());

    $conversations = Chat::conversation($conversation->id);

    //$dd = Chat::conversations($conversation)->for($user)->readAll();

    dd(Chat::conversations($conversations)->for($user)->getMessages()->where('body', 'asdfsadfsd'));

    //$message = Chat::messages($message)->for($user)->markRead();

    broadcast(new HasSeenMessage($message));

    return response('ok');
}

如何将类“未读”发送给元素 div 其他用户?我可以在当前用户上粘贴课程,并且只为我自己在元素聊天中获得颜色,但是当看到消息时,如何为我和其他用户隐藏元素?

我想为用户做读/未读功能。 示例:

如果用户实时发送消息我发送未读的课程,当其他用户点击文本区域时,我删除未读的课程,并且说用户,该消息被看到。我怎样才能实时添加/删除未读的类?我的功能不起作用。

【问题讨论】:

    标签: javascript laravel vue.js


    【解决方案1】:

    为此,您必须在您的 Laravel 应用程序中创建一个事件,您将在一个精确的频道上广播(例如,您可以命名为“聊天。{Conversation}。{User_id}”)并使用 Laravel Echo,您将听听这个活动!

    我允许自己对您的代码进行一些更改 -:)

    我想你有这个类 HasSeenEvent

      <?php 
         namespace App\Events;
    
         use App\Order;
         use Illuminate\Queue\SerializesModels;
         use Illuminate\Broadcasting\PrivateChannel;
         use Illuminate\Broadcasting\PresenceChannel; 
         use Illuminate\Broadcasting\InteractsWithSockets;
         use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
    
        class HasSeenEvent implements ShouldBroadcast
       {
         use SerializesModels;
    
        public $message;
    
        /**
         * Create a new event instance.
         *
         * @param  Message $message
         * @return void
         */
        public function __construct(Message $message)
        {
            $this->message = $message;
        }
    
        public function broadcastOn()
        {
            // I presume we can get conversation id like this : $this->message->conversation->id
            return new PrivateChannel('chat.'.$this->message->conversation->id.'.'.$this->message->sender->id);   
     }
    }
    

    然后,在你的 routes/broadcast.php 中声明这条路由 chat.{conversation}.{user_id}

    在您将“看到”设置为 1 的函数中,您同时广播事件

    broadcast(new HasSeenMessage($message))
    

    然后你在你的 vuejs 代码中监听这个事件

    components/Message.js

    <template>
    <li :class="className">
         {{ message }}
    </li>
    </template>
    
    <script>
    export default {
        props: [
            'message',
            'user',
            'time',
            'readed',
        ],
        computed: {
            className() {
                return this.readed == 1 ? 'seen' : 'unread';
            }
        },
        mounted() {
            console.log('Component mounted.')
        }
    }
    </script>
    

    chat.blade.php

        <message v-for="message,index in chat.messages" 
            :key="index" 
            :user="message.user"
            :message="message.content"
            :time="message.time"
            :readed="message.readed"
        >
        </message>
    
          <div class="form-group">
              <button type="button" class="btn btn-lg btn-primary" v-on:click="send">Send message</button>
          </div>
    

    App.js

    data: {
        message: '',
        convId: 1,
        chat: {
            messages: [],
         /*  message: [],
          user: [],
          time: [],
          seen: [], */
        },
        typing: '',
      },
    
      ....
    
    watch: {
        message() {
          Echo.private('chat')
            .whisper('typing', {
              name: this.message
            });
        }
      },
      methods: {
        send() {
          if (this.message.length != 0 && this.message.length <= 4000) {
           let data = {
            content: this.message,
            user: 'you',
            time:this.getTime(),
            readed: 0
           }
           this.chat.messages.push(data)
           data = {}
    
            axios.post('/sendMessage', {
                message: this.message,
                //lastName: 'Flintstone'
              })
              .then(response => {
                console.log(response);
                this.message = '';
              })
              .catch(error => {
                console.log(error);
              });
          }
        },
        seenMessage() {
          axios.post('/setMessagesSeen/' + this.convId) //this request mark messages in chat all readed for auhenticated user
            .then(response => {
               //This is not the best way to do that
                this.chat.messages[this.messages.length -1 ].readed = 0
             }).catch(response => {
                  console.log(response)
             })
        },
        getTime() {
                let time = new Date();
                return time.getHours() + ':' + time.getMinutes();
              }
         },
         mounted() {
              Echo.private('chat')
                .listen('ChatEvent', (e) => {
                    this.chat.messages.push({
                   content: e.message,
                   user: e.user,
                   time: this.getTime(),
                   readed: 0
                  })
                  console.log(e);
                })
                .listenForWhisper('typing', (e) => {
                  if (e.name != '')
                    this.typing = 'typing..';
                  else
                    this.typing = null;
                });
                // I presume to can access to user info
                let that = this
                Echo.private('chat.'+convId+'.'+user.id)
                     .listen('HasSeenMessage', (e) => {
                       let message = e.message
    
                       let lookingForMessage = that.chat.messages.find((m) => {
                  // I presume in your db messages table  has field content and time
                            return m.content == message.content && m.time => message.time
                       })
                       try {
                         lookingForMessage.readed = 1
                       }catch (err){
                         // message not found
                         console.log(err)
                       }
                     })
            }
    

    希望对你有所帮助!

    【讨论】:

    • 非常感谢!
    • 你能帮我看看我的功能吗?我更新了问题。我不知道如何正确获取消息并标记为已读。
    • 请提出一个新问题并发布您的聊天模型
    猜你喜欢
    • 2020-03-12
    • 2017-05-01
    • 1970-01-01
    • 2020-08-15
    • 2015-02-20
    • 1970-01-01
    • 2020-06-08
    • 2018-11-23
    • 2018-01-13
    相关资源
    最近更新 更多