当前位置:首页 > VUE

Vue 实现头条评论

2026-02-25 17:32:44VUE

Vue 实现头条评论功能

数据准备与绑定 使用 Vue 的 dataref(Composition API)存储评论列表和用户输入内容。例如:

data() {
  return {
    comments: [
      { id: 1, content: "第一条评论", likes: 10 },
      { id: 2, content: "第二条评论", likes: 5 }
    ],
    newComment: ""
  }
}

模板渲染 通过 v-for 渲染评论列表,结合 v-model 绑定输入框:

<div v-for="comment in comments" :key="comment.id">
  <p>{{ comment.content }}</p>
  <button @click="likeComment(comment.id)">点赞 {{ comment.likes }}</button>
</div>
<input v-model="newComment" placeholder="输入评论">
<button @click="addComment">提交</button>

交互逻辑 实现添加评论和点赞功能的方法:

methods: {
  addComment() {
    if (this.newComment.trim()) {
      this.comments.push({
        id: Date.now(),
        content: this.newComment,
        likes: 0
      });
      this.newComment = "";
    }
  },
  likeComment(id) {
    const comment = this.comments.find(c => c.id === id);
    if (comment) comment.likes++;
  }
}

优化与扩展功能

分页加载 结合 axios 实现分页请求,监听滚动事件加载更多:

async loadMore() {
  const res = await axios.get('/api/comments', { params: { page: this.page } });
  this.comments = [...this.comments, ...res.data];
  this.page++;
}

用户认证 在提交评论时检查登录状态:

addComment() {
  if (!this.$store.state.isLoggedIn) {
    alert("请先登录");
    return;
  }
  // 原有逻辑
}

样式与交互增强

悬浮效果 使用 CSS 增强交互体验:

.comment-item:hover {
  background-color: #f5f5f5;
  transition: background 0.3s;
}

时间格式化 显示评论发布时间,使用过滤器或计算属性:

filters: {
  formatDate(value) {
    return new Date(value).toLocaleString();
  }
}

模板中调用:

Vue 实现头条评论

<span>{{ comment.time | formatDate }}</span>

标签: 头条Vue
分享给朋友:

相关文章

Vue实现聊天软件

Vue实现聊天软件

Vue实现聊天软件的关键步骤 环境准备与项目初始化 使用Vue CLI或Vite创建Vue 3项目,安装必要依赖如vue-router、pinia(状态管理)、socket.io-client(实时通…

Vue 实现左右滑动

Vue 实现左右滑动

Vue 实现左右滑动的方法 使用 touch 事件监听 通过监听 touchstart、touchmove 和 touchend 事件实现基础滑动逻辑。在 Vue 组件中声明这些事件处理函数,计算滑动…

Vue悬浮球怎么实现

Vue悬浮球怎么实现

Vue悬浮球实现方法 使用CSS定位和Vue事件绑定 创建一个Vue组件,利用CSS的position: fixed属性固定悬浮球位置,结合Vue的@click、@touchstart等事件实现交互…

使用Vue实现洗牌动画

使用Vue实现洗牌动画

使用CSS和Vue实现洗牌动画 洗牌动画可以通过CSS过渡和Vue的动态数据绑定实现。以下是实现步骤: 准备数据 data() { return { cards: [ {…

纯Vue实现tab标签

纯Vue实现tab标签

Vue 实现 Tab 标签的步骤 基础结构 使用 Vue 的 v-for 和 v-show 或 v-if 实现动态渲染标签和内容。模板部分需包含标签头(tab headers)和内容区域(tab pa…

用Vue实现商品分类

用Vue实现商品分类

使用 Vue 实现商品分类 数据结构设计 商品分类通常采用树形结构,每个分类节点包含 id、name、children 等字段。例如: const categories = [ { id…