vue实现评论编辑
Vue 实现评论编辑功能
数据绑定与表单结构
在 Vue 中通过 v-model 实现双向数据绑定,创建一个编辑表单。例如:
<template>
<div v-if="isEditing">
<textarea v-model="editedContent"></textarea>
<button @click="saveEdit">保存</button>
<button @click="cancelEdit">取消</button>
</div>
<div v-else>
<p>{{ comment.content }}</p>
<button @click="startEdit">编辑</button>
</div>
</template>
编辑状态管理
通过 data 或 ref(Composition API)管理编辑状态和临时内容:

// Options API
data() {
return {
isEditing: false,
editedContent: ''
}
}
// Composition API
import { ref } from 'vue';
const isEditing = ref(false);
const editedContent = ref('');
方法实现
定义编辑相关方法,包括开始编辑、保存和取消操作:

methods: {
startEdit() {
this.editedContent = this.comment.content;
this.isEditing = true;
},
saveEdit() {
this.$emit('update-comment', {
id: this.comment.id,
content: this.editedContent
});
this.isEditing = false;
},
cancelEdit() {
this.isEditing = false;
}
}
父子组件通信
通过 props 接收评论数据,通过 $emit 提交修改:
props: {
comment: {
type: Object,
required: true
}
}
样式与用户体验
添加基础样式和交互反馈:
textarea {
width: 100%;
min-height: 100px;
padding: 8px;
}
button {
margin-right: 8px;
}
完整示例(Composition API)
<script setup>
import { ref } from 'vue';
const props = defineProps({
comment: Object
});
const emit = defineEmits(['update-comment']);
const isEditing = ref(false);
const editedContent = ref('');
const startEdit = () => {
editedContent.value = props.comment.content;
isEditing.value = true;
};
const saveEdit = () => {
emit('update-comment', {
id: props.comment.id,
content: editedContent.value
});
isEditing.value = false;
};
const cancelEdit = () => {
isEditing.value = false;
};
</script>






