使用vue写一个评论组件
时间: 2023-09-08 22:07:27 浏览: 62
好的,以下是一个简单的评论组件,使用Vue实现:
```
<template>
<div class="comment-section">
<h3>Comments</h3>
<ul>
<li v-for="(comment, index) in comments" :key="index">
<p class="comment-content">{{ comment }}</p>
<button @click="deleteComment(index)">Delete</button>
</li>
</ul>
<form @submit.prevent="submitComment">
<label for="new-comment">Add a comment:</label>
<input type="text" id="new-comment" v-model="newComment" required>
<button type="submit">Submit</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
comments: ["Great article!", "Thanks for sharing!", "I learned a lot."],
newComment: "",
};
},
methods: {
submitComment() {
if (this.newComment) {
this.comments.push(this.newComment);
this.newComment = "";
}
},
deleteComment(index) {
this.comments.splice(index, 1);
},
},
};
</script>
<style>
.comment-section {
font-family: Arial, sans-serif;
margin: 1rem;
}
.comment-content {
margin-bottom: 0.5rem;
}
button {
margin-left: 0.5rem;
}
</style>
```
该组件包含一个评论列表和一个表单,用户可以在表单中提交新的评论并删除现有评论。评论列表是用 `v-for` 指令渲染的,`v-model` 用于双向绑定表单输入。方法 `submitComment` 和 `deleteComment` 分别用于提交新评论和删除现有评论。
阅读全文