vue实现简单发表评论
Vue 实现发表评论功能
数据绑定与表单处理
在 Vue 中通过 v-model 实现表单双向绑定,创建一个评论输入框和提交按钮:
<template>
<div>
<textarea v-model="newComment" placeholder="输入评论内容"></textarea>
<button @click="addComment">发表评论</button>
</div>
</template>
<script>
export default {
data() {
return {
newComment: '',
comments: [] // 存储评论列表
}
}
}
</script>
提交逻辑处理
在 methods 中定义 addComment 方法,验证非空后添加到评论列表并清空输入框:
methods: {
addComment() {
if (this.newComment.trim() === '') return
this.comments.push({
id: Date.now(),
content: this.newComment,
timestamp: new Date().toLocaleString()
})
this.newComment = ''
}
}
评论列表渲染
使用 v-for 循环渲染评论列表,建议添加 key 提高性能:
<ul>
<li v-for="comment in comments" :key="comment.id">
<p>{{ comment.content }}</p>
<small>{{ comment.timestamp }}</small>
</li>
</ul>
样式优化(可选)
添加基础样式提升用户体验:
<style>
textarea {
width: 300px;
height: 100px;
margin-bottom: 10px;
}
button {
padding: 5px 15px;
}
ul {
list-style: none;
padding: 0;
}
li {
border-bottom: 1px solid #eee;
padding: 10px 0;
}
</style>
完整组件示例
<template>
<div class="comment-box">
<textarea v-model="newComment" placeholder="输入评论内容"></textarea>
<button @click="addComment">发表评论</button>
<ul class="comment-list">
<li v-for="comment in comments" :key="comment.id">
<p>{{ comment.content }}</p>
<small>{{ comment.timestamp }}</small>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
newComment: '',
comments: []
}
},
methods: {
addComment() {
if (this.newComment.trim() === '') return
this.comments.push({
id: Date.now(),
content: this.newComment,
timestamp: new Date().toLocaleString()
})
this.newComment = ''
}
}
}
</script>
<style>
/* 样式同上 */
</style>






