引言

Vue.js评论功能概述

1. 数据绑定

2. 模板语法

3. 事件处理

4. 表单验证

实现步骤

1. 项目搭建

首先,你需要创建一个 Vue.js 项目。可以使用 Vue CLI 工具快速搭建项目框架。

vue create comment-system
cd comment-system

2. 数据结构设计

data() {
  return {
    comments: [
      { id: 1, username: '用户1', content: '这是一条评论', likes: 10 },
      // ...其他评论
    ],
    newComment: {
      username: '',
      content: '',
    },
  };
},

3. 评论列表渲染

<template>
  <div>
    <ul>
      <li v-for="comment in comments" :key="comment.id">
        <p>{{ comment.username }}: {{ comment.content }}</p>
        <button @click="like(comment)">点赞 ({{ comment.likes }})</button>
      </li>
    </ul>
  </div>
</template>

4. 添加评论

<form @submit.prevent="addComment">
  <input v-model="newComment.username" placeholder="用户名">
  <textarea v-model="newComment.content" placeholder="评论内容"></textarea>
  <button type="submit">发表评论</button>
</form>

5. 表单验证

methods: {
  addComment() {
    if (this.newComment.username.trim() && this.newComment.content.trim()) {
      // ...添加评论逻辑
    } else {
      alert('请输入用户名和评论内容');
    }
  },
},

6. 事件处理

methods: {
  like(comment) {
    comment.likes++;
  },
  // ...删除评论等操作
},

总结