引言

一、准备工作

在开始之前,请确保你已经安装了Node.js和npm。然后,按照以下步骤创建一个新的Vue项目:

vue create comment-system
cd comment-system
npm run serve

二、设计评论系统

  • 显示评论列表
  • 添加评论
  • 删除评论

2.1 数据结构

  • id:唯一的标识符
  • author:评论者姓名
  • content:评论内容
  • date:评论日期

2.2 组件结构

  • CommentList:用于显示评论列表
  • CommentForm:用于添加评论
  • CommentItem:用于显示单个评论

三、实现评论列表

<template>
  <div>
    <comment-item
      v-for="comment in comments"
      :key="comment.id"
      :comment="comment"
    ></comment-item>
  </div>
</template>

<script>
import CommentItem from './CommentItem.vue';

export default {
  components: {
    CommentItem
  },
  data() {
    return {
      comments: [
        { id: 1, author: '张三', content: '这个网站很棒!', date: '2023-01-01' },
        { id: 2, author: '李四', content: '我也觉得很好用!', date: '2023-01-02' }
      ]
    };
  }
};
</script>

四、实现添加评论

<template>
  <div>
    <input v-model="newComment.author" placeholder="姓名" />
    <textarea v-model="newComment.content" placeholder="评论内容"></textarea>
    <button @click="addComment">发表评论</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      newComment: {
        author: '',
        content: ''
      }
    };
  },
  methods: {
    addComment() {
      if (this.newComment.author && this.newComment.content) {
        const newId = this.comments.length + 1;
        this.comments.push({
          id: newId,
          author: this.newComment.author,
          content: this.newComment.content,
          date: new Date().toLocaleDateString()
        });
        this.newComment.author = '';
        this.newComment.content = '';
      }
    }
  }
};
</script>

五、实现删除评论

<template>
  <div>
    <p>{{ comment.author }}:{{ comment.content }}</p>
    <button @click="deleteComment(comment.id)">删除</button>
  </div>
</template>

<script>
export default {
  props: {
    comment: {
      type: Object,
      required: true
    }
  },
  methods: {
    deleteComment(id) {
      const index = this.$parent.comments.findIndex(comment => comment.id === id);
      if (index !== -1) {
        this.$parent.comments.splice(index, 1);
      }
    }
  }
};
</script>

六、总结