vue3 写一个评论回复功能
时间: 2023-07-04 19:22:16 浏览: 87
好的,以下是一个基于 Vue3 的评论回复功能的示例代码:
```vue
<template>
<div>
<h2>评论</h2>
<textarea v-model="comment" placeholder="请输入评论"></textarea>
<button @click="submitComment">提交评论</button>
<hr>
<h3>评论列表</h3>
<ul>
<li v-for="(item, index) in comments" :key="index">
{{ item.content }}
<button @click="showReplyBox(index)">回复</button>
<div v-if="item.showReplyBox">
<textarea v-model="item.replyContent" placeholder="请输入回复"></textarea>
<button @click="submitReply(index)">提交回复</button>
</div>
<ul>
<li v-for="(reply, replyIndex) in item.replies" :key="replyIndex">
{{ reply.content }}
</li>
</ul>
</li>
</ul>
</div>
</template>
<script>
import { reactive } from 'vue'
export default {
setup() {
const state = reactive({
comment: '',
comments: [
{ content: '这是评论1', showReplyBox: false, replyContent: '', replies: [] },
{ content: '这是评论2', showReplyBox: false, replyContent: '', replies: [] },
{ content: '这是评论3', showReplyBox: false, replyContent: '', replies: [] },
],
})
// 显示回复框
const showReplyBox = (index) => {
state.comments[index].showReplyBox = true
}
// 提交评论
const submitComment = () => {
if (!state.comment.trim()) {
alert('请输入评论')
return
}
state.comments.push({ content: state.comment, showReplyBox: false, replyContent: '', replies: [] })
state.comment = ''
}
// 提交回复
const submitReply = (index) => {
if (!state.comments[index].replyContent.trim()) {
alert('请输入回复')
return
}
state.comments[index].replies.push({ content: state.comments[index].replyContent })
state.comments[index].replyContent = ''
state.comments[index].showReplyBox = false
}
return {
comment: state.comment,
comments: state.comments,
showReplyBox,
submitComment,
submitReply,
}
},
}
</script>
```
在这个示例中,我们使用了 Vue3 提供的 `reactive` 函数来创建响应式数据。评论和回复的内容都存储在 `comments` 数组中,每个评论对象中包含一个 `showReplyBox` 属性,用于控制回复框的显示状态,以及一个 `replies` 数组,用于存储回复内容。
用户输入评论或回复后,点击提交按钮即可将其添加到相应的评论对象或回复数组中。同时,为了方便用户回复,我们在每个评论对象中添加了一个按钮,点击后会显示回复框。
需要注意的是,为了防止用户输入空内容,我们在提交评论或回复前都进行了输入内容的判断。
这只是一个简单的示例代码,实际应用中可能还需要考虑更多的功能和细节。