在社交应用、即时通讯软件中,聊天界面卡片是一种常用的交互元素。它可以用来展示聊天记录、发送和接收消息等功能。
本段代码实现了 Vue 中一个基本的聊天界面卡片。它包括以下功能:
const messages = ref([
{
type: 'text',
content: 'I'm making a salad for dinner. How about you?',
time: '2:50 PM',
direction: 'right'
},
{
type: 'text',
content: 'I'm doing my homework, but I really need to take a break',
time: '4:18 PM',
direction: 'left'
},
{
type: 'text',
content: 'On my way home, but I needed to stop by the bookstore to buy a text book',
time: '6:39 PM',
direction: 'left'
}
]);
ref
声明一个可变的聊天记录数组。<div class="message-container">
<div v-for="message in messages" :key="message.content">
<div
:class="{
'message message-left': message.direction === 'left',
'message message-right': message.direction === 'right'
}"
>
<div class="message-text">{{ message.content }}</div>
<div class="message-time">{{ message.time }}</div>
</div>
</div>
</div>
v-for
遍历聊天记录数组,渲染每条消息。message-left
或 message-right
类,实现消息左右布局。<div class="flex flex-row h-16 w-full bg-white border-t border-gray-200">
<div class="flex flex-row items-center h-full w-1/6">
<div class="flex flex-row items-center h-full w-full">
<div class="flex flex-row items-center h-full w-1/2">
<van-icon name="mic" class="text-2xl text-gray-600" />
</div>
<div class="flex flex-row items-center h-full w-1/2">
<van-icon name="plus" class="text-2xl text-gray-600" />
</div>
</div>
</div>
<div class="flex flex-row items-center h-full w-5/6">
<div class="flex flex-row items-center h-full w-full">
<div class="flex flex-row items-center h-full w-1/2">
<input
type="text"
class="w-full h-full rounded-lg border border-gray-300 px-4 py-2 text-sm text-gray-600"
placeholder="Message..."
/>
</div>
<div class="flex flex-row items-center h-full w-1/2 justify-end">
<van-icon name="send-o" class="text-2xl text-gray-600" />
</div>
</div>
</div>
</div>
input
控件用于输入消息内容。van-icon
组件用于显示发送按钮。<script lang="tsx" setup>
import { ref } from 'vue';
const messages = ref([
// ...
]);
const sendMessage = () => {
// ...
};
</script>
setup
函数中定义 sendMessage
方法。sendMessage
方法中,获取输入框中的消息内容,并将其添加到聊天记录数组中。通过这段代码,我们实现了 Vue 中一个基本的聊天界面卡片。它具备了展示聊天记录、发送文本消息等基本功能。
ref
和 v-for
的使用,用于管理和渲染数据。