在v-for动态创建的项目vuejs中将不同的类应用于列表项

时间:2016-12-13 17:33:58

标签: vue.js

我想要做的就是将一个条件类应用于列表项,因为它被推送到我的messages数组,然后显示在屏幕上。但是,我不希望所有以前的列表项都应用相同的样式。每次添加新项目时,它都会检查应该应用哪个类,具体取决于消息的发件人或接收者,然后它适用于所有列表项所需的任何类,但我只希望它应用于该新项。我怎样才能做到这一点?

app.js:

const chatWindow = new Vue({
    el: '#chatWindow',
    data: {
        messages: [],
        currentUser: document.getElementById('sender').value,
        sender: true
    },
    methods: {
        sendMessage: function () {
            this.$http.post('/chat', {message: this.message, sender: this.currentUser}).then((response) => {
                console.log('request sent successfully');
            }, (response) => {
                console.log('request not sent');
            });

            this.message = '';
        }
    },
    props: ['message']
});

window.Echo.channel('test-chat-channel')
    .listen('MessageSent', (event) => {
        chatWindow.$data.sender = event.sender == chatWindow.$data.currentUser;
        chatWindow.$data.messages.push(event);
    });

chat.blade.php(查看):

@extends('layouts.app')

@section('content')
    <div class="container text-center">
        <div class="row">
            <div class="col-sm-3 hidden-xs" style="border: 2px solid black; height: 500px;">
                <h2 class="text-center no-top">Sidebar</h2>
            </div>
            <div id="chatWindow" class="col-sm-7">
                <h1 class="text-center no-top">Chat</h1>
                <div class="chat-window">
                    <input type="hidden" id="sender" value="{{ Auth::user()->id }}">
                    <ul id="chat-messages">
                        <li v-for="message in messages" :class="sender ? 'left' : 'right'">
                            @{{ message.message }}
                            <span class="pull-right">@{{ message.timestamp }}</span>
                        </li>
                    </ul>

                    <div class="form-group">
                        <input title="Send Message" v-model="message" @keyup.enter="sendMessage" class="form-control" placeholder="Send message...">
                    </div>
                </div>
            </div>
            <div class="col-sm-2 hidden-xs" style="border: 2px solid black; height: 500px;">
                <h2 class="text-center no-top">Infobar</h2>
            </div>
        </div>
    </div>
@endsection

@section('scripts')
@endsection

0 个答案:

没有答案