效果图:
代码:
html
<script setup lang="ts">
import { ref } from 'vue';
interface Message {
name: string;
phone: string;
message: string;
}
const name = ref<string>('');
const phone = ref<string>('');
const message = ref<string>('');
const messages = ref<Message[]>([]);
const submitMessage = () => {
if (name.value && phone.value && message.value) {
const phoneRegex = /^1[0123456789]\d{9}$/;
if (!phoneRegex.test(phone.value)) {
alert('请输入正确的手机号!');
return;
}
messages.value.unshift({
name: name.value,
phone: phone.value,
message: message.value
});
name.value = '';
phone.value = '';
message.value = '';
} else {
alert('请填写完整的信息!');
}
};
const deleteMessage = (index: number) => {
messages.value.splice(index, 1);
};
const editMessage = (index: number) => {
const editedMessage = prompt('请输入编辑后的留言内容:', messages.value[index].message);
if (editedMessage !== null) {
messages.value[index].message = editedMessage;
}
};
</script>
<template>
<div id="app">
<h1>留言板</h1>
<div class="message-form">
<label for="name">留言者姓名:</label>
<input type="text" v-model="name" placeholder="留言者姓名">
<label for="phone">手机号:</label>
<input type="text" v-model="phone" placeholder="手机号">
<label for="message">留言内容:</label>
<textarea v-model="message" placeholder="留言内容"></textarea>
<button @click="submitMessage">提交</button>
</div>
<div class="message-list" v-if="messages.length > 0">
<div v-for="(msg, index) in messages" :key="index" class="message">
<div>留言者姓名:{{ msg.name }}</div>
<div>手机号:{{ msg.phone }}</div>
<div>留言内容:{{ msg.message }}</div>
<button @click="deleteMessage(index)">删除</button>
<button @click="editMessage(index)">编辑</button>
</div>
</div>
</div>
</template>
<style scoped>
#app {
max-width: 600px;
margin: 0 auto;
padding: 20px;
font-family: 'Roboto', sans-serif;
}
h1 {
text-align: center;
margin-bottom: 20px;
color: #3498db;
}
.message-form {
display: flex;
flex-direction: column;
align-items: flex-start;
margin-bottom: 20px;
}
.message-form label {
width: 100%;
margin-bottom: 10px;
}
.message-form input,
.message-form textarea {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 14px;
}
.message-form button {
padding: 10px 20px;
background-color: #3498db;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 14px;
transition: all 0.3s ease;
display: block;
margin: 0 auto;
}
.message-form button:hover {
background-color: #2980b9;
}
.message-list {
margin-top: 20px;
}
.message {
background-color: #eef5f9;
border-left: 4px solid #007bff;
padding: 15px;
margin-bottom: 10px;
border-radius: 4px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.message button {
background-color: transparent;
color: #007bff;
border: 1px solid #007bff;
margin-right: 10px;
margin-top: 10px;
transition: background-color 0.3s ease, color 0.3s ease;
}
.message button:hover {
background-color: #007bff;
color: white;
}
</style>