黑马头条项目练习(day07)

本文展示了如何使用Vue.js构建一个文章详情页面,包括文章标题、作者信息、内容展示、评论列表、评论回复功能以及点赞、收藏和分享等交互。组件化设计包括CommentList、CommentPost、CommentReply等,实现了评论的增删查改和加载状态的管理。
摘要由CSDN通过智能技术生成

今天说到了文章评论,更新并新建了如下几个组件

首先是更新后了的index.vue

<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="page-nav-bar"
      left-arrow
      title="黑马头条"
      @click-left="$router.back()"
    ></van-nav-bar>
    <!-- /导航栏 -->

    <div class="main-wrap">
      <!-- 加载中 -->
      <div class="loading-wrap" v-if="loading">
        <van-loading color="#3296fa" vertical>加载中</van-loading>
      </div>
      <!-- /加载中 -->

      <!-- 加载完成-文章详情 -->
      <div class="article-detail" v-else-if="article.title">
        <!-- 文章标题 -->
        <h1 class="article-title">{{ article.title }}</h1>
        <!-- /文章标题 -->

        <!-- 用户信息 -->
        <van-cell class="user-info" center :border="false">
          <van-image
            class="avatar"
            slot="icon"
            round
            fit="cover"
            :src="article.aut_photo"
          />
          <div slot="title" class="user-name">{{ article.aut_name }}</div>
          <div slot="label" class="publish-date">
            {{ article.pubdate | relativeTime }}
          </div>
          <!-- <van-button
            @click="onFollow"
            v-if="article.is_followed"
            class="follow-btn"
            round
            size="small"
            :loading="followLoading"
            >已关注</van-button
          >
          <van-button
            @click="onFollow"
            v-else
            class="follow-btn"
            type="info"
            color="#3296fa"
            round
            size="small"
            icon="plus"
            :loading="followLoading"
            >关注</van-button
          > -->
          <!-- $event是用来接收子组件传过来的值 -->
          <!-- 在使用组件的同一个变量既要传递数据又要修改数据
          传递props:
                :is-followed="article.is_followed"
          修改:自定义事件
                @updataFollow="article.is_followed = $event"
           -->

          <!-- 可以使用简化形式 v-model -->
          <!-- 传递props:
                :value="article.is_followed"
              修改:内置封装 input
              @input="article.is_followed = $event"
           -->
          <!-- <FollowUser
            :isFollowed="article.is_followed"
            :followUserId="article.aut_id"
            @updataFollow="article.is_followed = $event"
          ></FollowUser> -->
          <FollowUser
            :followUserId="article.aut_id"
            v-model="article.is_followed"
          ></FollowUser>
        </van-cell>
        <!-- /用户信息 -->

        <!-- 文章内容 -->
        <div
          class="article-content markdown-body"
          v-html="article.content"
          ref="article-content"
        ></div>
        <van-divider>正文结束</van-divider>
        <!-- 评论列表开始 -->
        <CommentList
          @reply-click="onReplyClick"
          :list="commentLists"
          :source="article.art_id"
          @commentCounts="totalCommentCount = $event"
        ></CommentList>
        <!-- 评论列表结束 -->

        <!-- 发表评论的弹层开始 -->
        <van-popup v-model="isPostShow" position="bottom">
          <CommentPost
            :target="article.art_id"
            @onSuccessPost="onSuccessPost"
          ></CommentPost>
        </van-popup>
        <!-- 发表评论的弹层结束 -->

        <!-- 底部区域 -->
        <div class="article-bottom">
          <van-button
            @click="isPostShow = true"
            class="comment-btn"
            type="default"
            round
            size="small"
            >写评论</van-button
          >
          <van-icon name="comment-o" :info="totalCommentCount" color="#777" />
          <!-- <van-icon color="#777" name="star-o" /> -->
          <collectArticle
            v-model="article.is_collected"
            :articleId="article.art_id"
          ></collectArticle>
          <!-- 点赞区域开始 -->
          <!-- <van-icon color="#777" name="good-job-o" /> -->
          <LikeArticle
            class="btn-item"
            v-model="article.attitude"
            :article-id="article.art_id"
          ></LikeArticle>
          <!-- 点赞区域结束 -->
          <van-icon name="share" color="#777777"></van-icon>
        </div>
        <!-- /底部区域 -->
      </div>
      <!-- /加载完成-文章详情 -->

      <!-- 加载失败:404 -->
      <div class="error-wrap" v-else-if="errStatus === 404">
        <van-icon name="failure" />
        <p class="text">该资源不存在或已删除!</p>
      </div>
      <!-- /加载失败:404 -->

      <!-- 加载失败:其它未知错误(例如网络原因或服务端异常) -->
      <div class="error-wrap" v-else>
        <van-icon name="failure" />
        <p class="text">内容加载失败!</p>
        <van-button class="retry-btn" @click="loadArticleDetail"
          >点击重试</van-button
        >
      </div>
      <!-- /加载失败:其它未知错误(例如网络原因或服务端异常) -->
    </div>

    <!-- 回复评论的弹层开始 -->
    <!-- van-popup: 是懒加载的,只会在页面展开的时候渲染一次内容,打开和关闭弹层,只是对内容进行显示和隐藏 -->
    <!-- 所以利用v-if的创建销毁组件的特性来达到更新数据的目的 -->
    <van-popup v-model="isReplyShow" position="bottom" style="height: 100%">
      <CommentReply
        v-if="isReplyShow"
        :comment="currentComment"
        @close-reply="isReplyShow = false"
      ></CommentReply>
    </van-popup>
    <!-- 回复评论的弹层结束 -->
  </div>
</template>

<script>
import CommentReply from "./components/comment-reply";
import CommentPost from "./components/comment-post";
import LikeArticle from "@/components/like-article";
import CommentList from "./components/comment-list";
import collectArticle from "@/components/collect-article";
import FollowUser from "@/components/follow-user";
// import { addFollowAPI, deleteFollowAPI } from "@/api";
import { getArticleByIdAPI } from "@/api";
import { ImagePreview } from "vant";
// vant的ImagePreview配置代码
// ImagePreview({
//   images: [
//     "https://img01.yzcdn.cn/vant/apple-1.jpg",
//     "https://img01.yzcdn.cn/vant/apple-2.jpg",
//   ],
//   startPosition: 1,
//   closeable: true,
//   onClose() {
//     this.$toast("关闭");
//   },
// });
export default {
  name: "ArticleIndex",
  components: {
    FollowUser,
    collectArticle,
    CommentList,
    LikeArticle,
    CommentPost,
    CommentReply,
  },
  props: {
    // 使用props获取动态路由的数据
    articleId: {
      type: [Number, String],
      required: true,
    },
  },
  // 给所有的后代组件提供数据
  // 注意:不要滥用
  provide: function () {
    return {
      articleId: this.articleId, // 或者写成 this.$route.params.articleId  也可以
    };
  },
  data() {
    return {
      article: {},
      loading: true, // 加载中的状态
      errStatus: 0, // 存储错误的状态码
      followLoading: false, // 控制加载中的状态
      totalCommentCount: 0, // 存储评论总数
      isPostShow: false, // 弹层显示
      commentLists: [], // 存储文章评论的
      isReplyShow: false, // 控制评论的弹层的显示和隐藏
      currentComment: {}, // 当前点击回复的评论项
    };
  },
  computed: {},
  watch: {},
  created() {
    this.loadArticle();
  },
  mounted() {},
  methods: {
    // 3. 定义获取数据请求方法
    async loadArticle() {
      // 开启加载中的状态
      this.loading = true;

      try {
        // 手动抛出错误,测试功能
        // if (Math.random() > 0.6) {
        //   throw new Error("错误");
        // }
        // 3.1 发送请求
        const { data } = await getArticleByIdAPI(this.articleId);
        // 3.3 成功赋值
        this.article = data.data; // vue的dom更新是异步的

        setTimeout(() => {
          // 在数据更新之后,调用图片预览功能
          this.previewImage();
        }, 0);

        console.log(this.article); // 控制台查看数据输出
      } catch (err) {
        // 3.2 失败处理
        if (err.response && err.response.status === 404) {
          this.errStatus = 404;
          this.$toast("访问的文章资源不存在");
        } else {
          this.$toast("获取文章详情失败");
          console.log(err);
        }
      }
      // 关闭加载中的状态
      this.loading = false;
    },
    loadArticleDetail() {
      this.loadArticle();
    },
    previewImage() {
      // 得到所有的 img 节点
      const articleContent = this.$refs["article-content"]; // 获取到了容器节点
      const imgs = articleContent.querySelectorAll("img");
      // 存储文章内容中的所有图片地址
      const images = [];

      // 遍历所有的图片,拿到每个图片的地址
      imgs.forEach((img, index) => {
        // 把图片地址push进images数组里
        images.push(img.src);

        // 给每个图片添加一个点击事件,调用ImagePreview图片预览功能
        img.onclick = () => {
          ImagePreview({
            images: images,
            // 指定预览图片的起始位置
            startPosition: index,
          });
        };
      });
    },
    // 关注用户,和取消关注
    // async onFollow() {
    //   this.followLoading = true;
    //   // 判断用户是否登录,如果没有请先登录才能操作
    //   if (!this.$store.state.user) return this.$toast("请先登录");

    //   // 发送请求实现登录(添加关注,和取消关注)
    //   try {
    //     const AutId = this.article.aut_id;
    //     // 判断是否已经关注了
    //     if (this.article.is_followed) {
    //       await deleteFollowAPI(AutId);
    //     } else {
    //       await addFollowAPI(AutId);
    //     }
    //     // 更新视图
    //     this.article.is_followed = !this.article.is_followed;
    //   } catch (err) {
    //     if (err && err.response.status === 400) {
    //       this.$toast("用户不能关注自己");
    //     } else {
    //       this.$toast("请求失败");
    //     }
    //   }
    //   this.followLoading = false;
    // },
    // 关闭发表文章评论弹层
    onSuccessPost(comment) {
      console.log(comment);
      this.commentLists.unshift(comment.new_obj);
      this.isPostShow = false;
    },
    // 打开弹层并接收评论对象
    onReplyClick(comment) {
      console.log(comment);
      // 保存评论对象到data变量中
      this.currentComment = comment;
      // 打开回复的弹层
      this.isReplyShow = true;
    },
  },
};
</script>

<style scoped lang="less">
@import "./github-markdown.css";
.article-container {
  .main-wrap {
    position: fixed;
    left: 0;
    right: 0;
    top: 92px;
    bottom: 88px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-detail {
    .article-title {
      font-size: 40px;
      padding: 50px 32px;
      margin: 0;
      color: #3a3a3a;
    }

    .user-info {
      padding: 0 32px;
      .avatar {
        width: 70px;
        height: 70px;
        margin-right: 17px;
      }
      .van-cell__label {
        margin-top: 0;
      }
      .user-name {
        font-size: 24px;
        color: #3a3a3a;
      }
      .publish-date {
        font-size: 23px;
        color: #b7b7b7;
      }
      .follow-btn {
        width: 170px;
        height: 58px;
      }
    }

    .article-content {
      padding: 55px 32px;
      /deep/ p {
        text-align: justify;
      }
    }
  }

  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 200px 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    .van-icon {
      font-size: 122px;
      color: #b4b4b4;
    }
    .text {
      font-size: 30px;
      color: #666666;
      margin: 33px 0 46px;
    }
    .retry-btn {
      width: 280px;
      height: 70px;
      line-height: 70px;
      border: 1px solid #c3c3c3;
      font-size: 30px;
      color: #666666;
    }
  }

  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 88px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
    .comment-btn {
      width: 282px;
      height: 46px;
      border: 2px solid #eeeeee;
      font-size: 30px;
      line-height: 46px;
      color: #a7a7a7;
    }
    .van-icon {
      font-size: 40px;
      .van-info {
        font-size: 16px;
        background-color: #e22829;
      }
    }
  }
}
</style>

然后就是comment-item.vue

<template>
  <van-cell class="comment-item">
    <van-image
      slot="icon"
      class="avatar"
      round
      fit="cover"
      :src="comment.aut_photo"
    />
    <div slot="title" class="title-wrap">
      <div class="user-name">{{ comment.aut_name }}</div>
      <van-button
        @click="OnClickLike"
        :class="{ liked: comment.is_liking }"
        :loading="likeLoading"
        class="like-btn"
        :icon="comment.is_liking ? 'good-job' : 'good-job-o'"
        >{{ comment.like_count > 0 ? comment.like_count : "赞" }}</van-button
      >
    </div>

    <div slot="label">
      <p class="comment-content">{{ comment.content }}</p>
      <div class="bottom-info">
        <span class="comment-pubdate">{{
          comment.pubdate | relativeTime
        }}</span>
        <van-button
          @click="$emit('reply-click', comment)"
          class="reply-btn"
          round
          >回复 {{ comment.reply_count }}</van-button
        >
      </div>
    </div>
  </van-cell>
</template>

<script>
import { addCommentLikeAPI, deleteCommentLikeAPI } from "@/api";
export default {
  name: "CommentItem",
  props: {
    //每行的评论信息
    comment: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      likeLoading: false,
    };
  },
  methods: {
    async OnClickLike() {
      this.likeLoading = true;
      // 判断是否登录,没有登录先登录
      if (!this.$store.state.user) return this.$toast("请先登录");
      try {
        // 判断是否已经点赞
        if (this.comment.is_liking) {
          // 有 取消
          await addCommentLikeAPI(this.comment.com_id);
          this.comment.like_count--;
        } else {
          // 没有 赞
          await deleteCommentLikeAPI(this.comment.com_id);
          this.comment.like_count++;
        }
        this.comment.is_liking = !this.comment.is_liking;
      } catch (error) {
        console.log(error);
        this.$toast("点赞失败");
      }
      this.likeLoading = false;
    },
  },
};
</script>

<style scoped lang="less">
.comment-item {
  .avatar {
    width: 72px;
    height: 72px;
    margin-right: 25px;
  }
  .title-wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .user-name {
      color: #406599;
      font-size: 26px;
    }
  }
  .comment-content {
    font-size: 32px;
    color: #222222;
    word-break: break-all;
    text-align: justify;
  }
  .comment-pubdate {
    font-size: 19px;
    color: #222;
    margin-right: 25px;
  }
  .bottom-info {
    display: flex;
    align-items: center;
  }
  .reply-btn {
    width: 135px;
    height: 48px;
    line-height: 48px;
    font-size: 21px;
    color: #222;
  }
  .like-btn {
    height: 30px;
    padding: 0;
    border: none;
    font-size: 19px;
    line-height: 30px;
    margin-right: 7px;
    .van-icon {
      font-size: 30px;
    }
  }
  .liked {
    background-color: orange;
  }
}
</style>

然后再就是comment-list.vue

<template>
  <van-cell class="comment-item">
    <van-image
      slot="icon"
      class="avatar"
      round
      fit="cover"
      :src="comment.aut_photo"
    />
    <div slot="title" class="title-wrap">
      <div class="user-name">{{ comment.aut_name }}</div>
      <van-button
        @click="OnClickLike"
        :class="{ liked: comment.is_liking }"
        :loading="likeLoading"
        class="like-btn"
        :icon="comment.is_liking ? 'good-job' : 'good-job-o'"
        >{{ comment.like_count > 0 ? comment.like_count : "赞" }}</van-button
      >
    </div>

    <div slot="label">
      <p class="comment-content">{{ comment.content }}</p>
      <div class="bottom-info">
        <span class="comment-pubdate">{{
          comment.pubdate | relativeTime
        }}</span>
        <van-button
          @click="$emit('reply-click', comment)"
          class="reply-btn"
          round
          >回复 {{ comment.reply_count }}</van-button
        >
      </div>
    </div>
  </van-cell>
</template>

<script>
import { addCommentLikeAPI, deleteCommentLikeAPI } from "@/api";
export default {
  name: "CommentItem",
  props: {
    //每行的评论信息
    comment: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      likeLoading: false,
    };
  },
  methods: {
    async OnClickLike() {
      this.likeLoading = true;
      // 判断是否登录,没有登录先登录
      if (!this.$store.state.user) return this.$toast("请先登录");
      try {
        // 判断是否已经点赞
        if (this.comment.is_liking) {
          // 有 取消
          await addCommentLikeAPI(this.comment.com_id);
          this.comment.like_count--;
        } else {
          // 没有 赞
          await deleteCommentLikeAPI(this.comment.com_id);
          this.comment.like_count++;
        }
        this.comment.is_liking = !this.comment.is_liking;
      } catch (error) {
        console.log(error);
        this.$toast("点赞失败");
      }
      this.likeLoading = false;
    },
  },
};
</script>

<style scoped lang="less">
.comment-item {
  .avatar {
    width: 72px;
    height: 72px;
    margin-right: 25px;
  }
  .title-wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .user-name {
      color: #406599;
      font-size: 26px;
    }
  }
  .comment-content {
    font-size: 32px;
    color: #222222;
    word-break: break-all;
    text-align: justify;
  }
  .comment-pubdate {
    font-size: 19px;
    color: #222;
    margin-right: 25px;
  }
  .bottom-info {
    display: flex;
    align-items: center;
  }
  .reply-btn {
    width: 135px;
    height: 48px;
    line-height: 48px;
    font-size: 21px;
    color: #222;
  }
  .like-btn {
    height: 30px;
    padding: 0;
    border: none;
    font-size: 19px;
    line-height: 30px;
    margin-right: 7px;
    .van-icon {
      font-size: 30px;
    }
  }
  .liked {
    background-color: orange;
  }
}
</style>

然后再就是comment-post.vue

<template>
  <div class="comment-post">
    <van-field
      class="post-field"
      v-model.trim="message"
      rows="2"
      autosize
      type="textarea"
      maxlength="50"
      placeholder="请输入留言"
      show-word-limit
    />
    <van-button
      class="post-btn"
      @click="onPostComment"
      :disabled="!message.length"
      >发布</van-button
    >
  </div>
</template>

<script>
import { addCommentAPI } from "@/api";
export default {
  name: "CommentPost",
  data() {
    return {
      message: "",
    };
  },
  inject: {
    articleId: {
      type: [String, Number],
      default: null,
    },
  },
  props: {
    target: {
      type: [String, Number],
      required: true,
    },
    // 自定义了一个type属性,用来判断是文章评论还是评论的回复
    type: {
      type: String,
      default: "a",
    },
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    // 发表评论
    async onPostComment() {
      // 1. 发送请求发表评论
      this.$toast.loading({
        message: "发布中...",
        forbidClick: true,
        duration: 0, //不关闭,直到下一个toast调用
      });
      try {
        const { data } = await addCommentAPI({
          target: this.target, // 评论目标id(评论文章即文章id,对评论进行回复则为评论id)
          content: this.message, // 评论内容
          art_id: this.type === "c" ? this.articleId : null, // 文章id,对评论内容发表回复时,需要传递此参数,表明所属文章id。对文章进行评论,不要传此参数。
        });
        // 2. 请求成功
        console.log(data.data);
        // 2.1 清空输入框内容
        this.message = ""; // 发布成功后让评论区为空
        // 2.2 关闭弹层
        this.$emit("onSuccessPost", data.data);
        // 2.3 发布的评论显示出来
        this.$toast("评论发布成功");
      } catch (error) {
        // 3. 请求失败
        console.log(error);
        this.$toast("发表评论失败");
      }
    },
  },
};
</script>

<style scoped lang="less">
.comment-post {
  display: flex;
  align-items: center;
  padding: 32px 0 32px 32px;
  .post-field {
    background-color: #f5f7f9;
  }
  .post-btn {
    width: 150px;
    border: none;
    padding: 0;
    color: #6ba3d8;
    &::before {
      display: none;
    }
  }
}
</style>

然后再就是comment-reply.vue

<template>
  <div class="comment-reply">
    <!-- 标题开始 -->
    <van-nav-bar class="page-nav-bar">
      <div slot="title">
        {{
          comment.reply_count > 0
            ? `有${comment.reply_count}条回复`
            : "暂无回复"
        }}
      </div>
      <template #right>
        <van-icon name="cross" @click="$emit('close-reply')" />
      </template>
    </van-nav-bar>
    <!-- 标题结束 -->
    <div class="scroll-wrap">
      <!-- 评论项内容开始 -->
      <van-cell title="评论项内容" style="background: #fafafa"></van-cell>
      <commentItem :comment="comment"></commentItem>
      <!-- 评论项内容结束 -->
      <!-- 回复列表开始 -->
      <van-cell title="回复列表" style="background: #fafafa"></van-cell>
      <commentList
        :list="commentList"
        :source="comment.com_id"
        type="c"
      ></commentList>
      <!-- 回复列表结束 -->

      <!-- 底部区域 -->
      <div class="reply-bottom">
        <van-button
          class="write-btn"
          size="small"
          round
          @click="isReplyShow = true"
          >写评论</van-button
        >
      </div>
      <!-- /底部区域 -->

      <!-- 发布评论回复的弹出层开始 -->
      <van-popup v-model="isReplyShow" position="bottom">
        <commentPost
          @onSuccessPost="onSuccessPost"
          :target="comment.com_id"
          type="c"
        ></commentPost>
      </van-popup>
      <!-- 发布评论回复的弹出层结束 -->
    </div>
  </div>
</template>

<script>
import commentItem from "./comment-item.vue";
import commentList from "./comment-list.vue";
import commentPost from "./comment-post.vue";
export default {
  name: "CommentReply",
  components: {
    commentItem,
    commentList,
    commentPost,
  },
  props: {
    comment: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      isReplyShow: false, // 控制弹层的关闭和显示
      commentList: [],
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    onSuccessPost(comment) {
      console.log(comment);
      this.commentList.unshift(comment.new_obj);
      this.isReplyShow = false;
    },
  },
};
</script>
<style scoped lang="less">
.scroll-wrap {
  position: fixed;
  top: 92px;
  left: 0;
  right: 0;
  bottom: 88px;
  overflow-y: auto;
}

.reply-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 88px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border-top: 1px solid #d8d8d8;
  .write-btn {
    width: 60%;
  }
}
</style>

over!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

孙大大啊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值