Reputation: 13
I'm trying to make a chat based on this link: https://socket.io/get-started/private-messaging-part-1/
and I'm hoping to style it such that when the message is from self, the message will have a grey background instead of white.
However right now, regardless of whether the message is from self or not, they are in the same class (message) and editing the color in this class will simply both background. Is there a way to add conditional styling?
Under template:
<ul class="messages">
<li
v-for="(message, index) in user.messages"
:key="index"
class="message"
>
<div v-if="displaySender(message, index)" class="sender">
{{ message.fromSelf ? "(yourself)" : user.username }}
</div>
{{ message.content }}
</li>
</ul>
Under style:
.message {
list-style: none;
background-color: white;
border: solid;
border-color: gray;
border-width: 1px;
border-radius: 15px;
margin-bottom: 10px;
padding: 10px;
}
Upvotes: 1
Views: 2339
Reputation: 285403
Create a dynamic class, :class=...
based on the state of message.fromSelf
, and set styling for the HTML element to be based on the class.
For example, if we created a dynamic class,
:class="message.fromSelf ? 'self-message' : ''"
Or better still (thanks to suggestion from Wittgenstein)
:class="{ 'self-message': message.fromSelf }"
and then added styling for it:
.self-message {
background-color: gray;
}
It could look like so:
Functioning small example program:
<script>
import { ref } from "vue";
export default {
data() {
return {
messages: [
{
fromSelf: true,
content: "Hello folks!",
username: ''
},
{
fromSelf: false,
content: "Hello, back to you!",
username: 'John'
},
{
fromSelf: true,
content: "How are you doing?",
username: ''
},
{
fromSelf: false,
content: "I'm doing very well here, you?",
username: 'John'
},
],
};
},
};
</script>
<template>
<ul class="messages">
<li
v-for="(message, index) in messages"
:key="index"
:class="{ 'self-message': message.fromSelf, 'message': true }"
>
<div class="sender">
{{ message.fromSelf ? "(yourself)" : message.username + ":" }}
</div>
{{ message.content }}
</li>
</ul>
</template>
<style>
.message {
list-style: none;
background-color: white;
border: solid;
border-color: gray;
border-width: 1px;
border-radius: 15px;
margin-bottom: 10px;
padding: 10px;
}
.self-message {
background-color: lightgray;
}
</style>
Upvotes: 3