vue实现评论发送
Vue 实现评论发送功能
数据绑定与表单结构
在 Vue 中通过 v-model 实现双向数据绑定,创建评论输入框和提交按钮。示例模板结构:
<template>
<div class="comment-box">
<textarea v-model="commentText" placeholder="输入评论内容"></textarea>
<button @click="submitComment">发送评论</button>
</div>
</template>
数据与事件处理
在 Vue 实例中定义数据属性和提交方法:

<script>
export default {
data() {
return {
commentText: '',
comments: [] // 存储已提交的评论
}
},
methods: {
submitComment() {
if (this.commentText.trim()) {
this.comments.push({
id: Date.now(),
content: this.commentText,
timestamp: new Date()
})
this.commentText = '' // 清空输入框
}
}
}
}
</script>
评论列表展示
使用 v-for 渲染评论列表:
<ul class="comment-list">
<li v-for="comment in comments" :key="comment.id">
<p>{{ comment.content }}</p>
<span>{{ comment.timestamp.toLocaleString() }}</span>
</li>
</ul>
样式优化
添加基础样式提升用户体验:

<style scoped>
.comment-box textarea {
width: 100%;
height: 80px;
margin-bottom: 10px;
}
button {
padding: 8px 16px;
background: #42b983;
color: white;
border: none;
}
.comment-list li {
border-bottom: 1px solid #eee;
padding: 10px 0;
}
</style>
后端交互(可选)
如需保存到服务器,可使用 axios 发送请求:
import axios from 'axios'
methods: {
async submitComment() {
try {
const res = await axios.post('/api/comments', {
content: this.commentText
})
this.comments.unshift(res.data) // 将新评论添加到列表开头
this.commentText = ''
} catch (error) {
console.error('提交失败', error)
}
}
}
输入验证
添加基础验证逻辑:
submitComment() {
if (!this.commentText.trim()) {
alert('评论内容不能为空')
return
}
if (this.commentText.length > 200) {
alert('评论不得超过200字')
return
}
// 正常提交逻辑...
}






