vue 实现回复
Vue 实现回复功能
在 Vue 中实现回复功能通常涉及表单提交、数据绑定和列表渲染。以下是实现步骤和代码示例:
数据绑定与表单
<template>
<div>
<form @submit.prevent="handleSubmit">
<input v-model="replyContent" placeholder="输入回复内容" />
<button type="submit">提交</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
replyContent: '',
replies: []
}
},
methods: {
handleSubmit() {
if (this.replyContent.trim()) {
this.replies.push({
id: Date.now(),
content: this.replyContent,
timestamp: new Date()
})
this.replyContent = ''
}
}
}
}
</script>
渲染回复列表
<template>
<div>
<ul>
<li v-for="reply in replies" :key="reply.id">
{{ reply.content }}
<span class="timestamp">{{ formatDate(reply.timestamp) }}</span>
</li>
</ul>
</div>
</template>
<script>
export default {
methods: {
formatDate(date) {
return new Date(date).toLocaleString()
}
}
}
</script>
样式优化
<style scoped>
.timestamp {
color: #666;
font-size: 0.8em;
margin-left: 10px;
}
</style>
嵌套回复实现
对于多级回复功能,需要递归组件:
<template>
<div>
<comment
v-for="comment in comments"
:key="comment.id"
:comment="comment"
/>
</div>
</template>
创建递归组件 Comment.vue:
<template>
<div class="comment">
<div>{{ comment.content }}</div>
<button @click="showReplyForm = !showReplyForm">回复</button>
<div v-if="showReplyForm">
<input v-model="replyText" />
<button @click="addReply">提交</button>
</div>
<div class="replies" v-if="comment.replies">
<comment
v-for="reply in comment.replies"
:key="reply.id"
:comment="reply"
/>
</div>
</div>
</template>
<script>
export default {
name: 'Comment',
props: {
comment: Object
},
data() {
return {
showReplyForm: false,
replyText: ''
}
},
methods: {
addReply() {
if (!this.replyText.trim()) return
const newReply = {
id: Date.now(),
content: this.replyText,
replies: []
}
if (!this.comment.replies) {
this.$set(this.comment, 'replies', [])
}
this.comment.replies.push(newReply)
this.replyText = ''
this.showReplyForm = false
}
}
}
</script>
后端数据交互
与后端API交互的示例:
methods: {
async fetchComments() {
try {
const response = await axios.get('/api/comments')
this.comments = response.data
} catch (error) {
console.error('获取评论失败:', error)
}
},
async submitComment() {
try {
const response = await axios.post('/api/comments', {
content: this.newComment
})
this.comments.unshift(response.data)
this.newComment = ''
} catch (error) {
console.error('提交评论失败:', error)
}
}
}






