经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » Vue.js » 查看文章
《花100块做个摸鱼小网站! 》第四篇—前端应用搭建和完成第一个热搜组件
来源:cnblogs  作者:sum墨  时间:2024/8/26 9:16:49  对本文有异议

??基础链接导航??

服务器 → ?? 阿里云活动地址

看样例 → ?? 摸鱼小网站地址

学代码 → ?? 源码库地址

一、前言

在本系列文章的早期章节中,我们已经成功地购买了服务器并配置了MySQL、Redis等核心中间件。紧接着,我们不仅建立了后端服务,还开发了我们的首个爬虫程序。后面我们还把爬取到的数据进行了保存,生成了一整套MVC的后端代码,并且提供了一个接口出来。

这篇文章呢我要开始前端开发部分了。与后端开发相比,前端开发的优势在于其直观性和即时反馈。开发者可以迅速看到自己代码的成果,这种“所见即所得”的体验极大地提升了开发的乐趣和满足感。在接下来的篇章中,我将展示如何将爬取到的热搜数据整合到前端界面中,使之以一种用户友好的方式呈现,大家姑妄看之。

二、前端应用搭建

我的前端技术栈还停留在四年前,那时候我主要使用的是Vue2和ElementUI。并不是说我认为Vue3或React不好,只是我更习惯使用我熟悉的技术。即便如此,这些技术依然能够带来不错的效果。如果你想要尝试不同的技术或组件库,那也是完全可以的。

1. 前端环境搭建

(1)安装node.js,下载相应版本的node.js,下载地址:https://nodejs.org/en/download/ ,下载完双击安装,点击下一步直到安装完成,建议下载版本的是:v16.20.2

(2)安装完成后,附件里选择命令提示符(或者在开始的搜索框里输入cmd回车调出命令面板)输入:node -v回车,出现相应版本证明安装成功, node环境已经安装完成。

由于有些npm有些资源被屏蔽或者是国外资源的原因,经常会导致用npm安装依赖包的时候失败,所有我还需要npm的 国内镜像---cnpm。在命令行中输入:npm install -g cnpm --registry=https://registry.npmmirror.com 回车,大约需要3分钟,如果一直没有反应使用管理员身份运行cmd重试。

(3)安装全局vue-cli脚手架,用于帮助搭建所需的模板框架。输入命令:cnpm install -g @vue/cli回车等待完成。

(4)创建项目,首先我们要选定目录,然后再命令行中把目录转到选定的目录,假如我们打算把项目新建在e盘下的vue文件夹中则输入下面的命令: e:回车,然后cd vue,然后输入命令:vue create summo-sbmy-front-web,回车,然后它就会让你选择vue2还是vue3,选择vue2后点击enter,它就会创建好项目并且下载好依赖。

(5)启动项目,首先切换到summo-sbmy-front-web目录,然后执行npm run serve,项目运行成功后,浏览器会自动打开localhost:8080(如果浏览器没有自动打开 ,可以手动输入)。运行成功后,会看到Welcome to Your Vue.js App页面。

2. 脚手架处理

我的开发工具是VS Code,免费的,下载地址如下:https://code.visualstudio.com/

(1)文件和代码清理

删除components下的HelloWorld.vue文件
删除assets下的logo.png文件

原始App.vue代码如下

  1. <template>
  2. <div id="app">
  3. <img alt="Vue logo" src="./assets/logo.png">
  4. <HelloWorld msg="Welcome to Your Vue.js App"/>
  5. </div>
  6. </template>
  7. <script>
  8. import HelloWorld from './components/HelloWorld.vue'
  9. export default {
  10. name: 'App',
  11. components: {
  12. HelloWorld
  13. }
  14. }
  15. </script>
  16. <style>
  17. #app {
  18. font-family: Avenir, Helvetica, Arial, sans-serif;
  19. -webkit-font-smoothing: antialiased;
  20. -moz-osx-font-smoothing: grayscale;
  21. text-align: center;
  22. color: #2c3e50;
  23. margin-top: 60px;
  24. }
  25. </style>

删除不必要的代码,不然启动会报错

  1. <template>
  2. <div id="app">
  3. </div>
  4. </template>
  5. <script>
  6. export default {
  7. name: 'App',
  8. components: {
  9. }
  10. }
  11. </script>
  12. <style>
  13. #app {
  14. font-family: Avenir, Helvetica, Arial, sans-serif;
  15. -webkit-font-smoothing: antialiased;
  16. -moz-osx-font-smoothing: grayscale;
  17. text-align: center;
  18. color: #2c3e50;
  19. margin-top: 60px;
  20. }
  21. </style>

(2)axios和element-ui依赖引入

执行安装命令

  1. //axios依赖引入
  2. cnpm install axios
  3. //element-ui依赖引入
  4. cnpm install element-ui

下载完上面这两个组件后,去main.js中注册组件,然后才能使用,main.js代码如下:

  1. import Vue from 'vue'
  2. import App from './App.vue'
  3. //引入饿了么UI
  4. import {
  5. Calendar,
  6. Row,
  7. Col,
  8. Link,
  9. Button,
  10. Loading,
  11. Container,
  12. Header,
  13. Footer,
  14. Main,
  15. Form,
  16. Autocomplete,
  17. Tooltip,
  18. Card,
  19. Dialog
  20. } from 'element-ui';
  21. Vue.use(Calendar)
  22. Vue.use(Row)
  23. Vue.use(Col)
  24. Vue.use(Link)
  25. Vue.use(Button)
  26. Vue.use(Loading)
  27. Vue.use(Container)
  28. Vue.use(Header)
  29. Vue.use(Footer)
  30. Vue.use(Form)
  31. Vue.use(Autocomplete)
  32. Vue.use(Tooltip)
  33. Vue.use(Card)
  34. Vue.use(Main)
  35. Vue.use(Dialog)
  36. import "element-ui/lib/theme-chalk/index.css"
  37. //引入axios
  38. import axios from 'axios';
  39. Vue.prototype.$ajax = axios;
  40. Vue.config.productionTip = false
  41. new Vue({
  42. render: h => h(App),
  43. }).$mount('#app')

(3)封装apiService.js方便调用接口

在src目录下创建一个文件夹名为config,创建一个apiService.js,代码如下:

  1. // apiService.js
  2. import axios from "axios";
  3. // 创建axios实例并配置基础URL
  4. const apiClient = axios.create({
  5. baseURL: "http://localhost:80/api",
  6. headers: {
  7. "Content-Type": "application/json"
  8. },
  9. });
  10. export default {
  11. // 封装Get接口
  12. get(fetchUrl) {
  13. return apiClient.get(fetchUrl);
  14. }
  15. };

三、前端热搜组件

1. 组件介绍

首先,成品的热搜组件样式如下,包括标题(图标+名称)、内容区(排序、标题、热度),点击标题可以跳转到指定的热搜文章。

2. 组件实现

在components目录下创建HotSearchBoard.vue文件,代码如下:

  1. <template>
  2. <el-card class="custom-card" v-loading="loading">
  3. <template #header>
  4. <div class="card-title">
  5. <img :src="icon" class="card-title-icon" />
  6. {{ title }}热榜
  7. </div>
  8. </template>
  9. <div class="cell-group-scrollable">
  10. <div
  11. v-for="item in hotSearchData"
  12. :key="item.hotSearchOrder"
  13. :class="getRankingClass(item.hotSearchOrder)"
  14. class="cell-wrapper"
  15. >
  16. <span class="cell-order">{{ item.hotSearchOrder }}</span>
  17. <span
  18. class="cell-title hover-effect"
  19. @click="openLink(item.hotSearchUrl)"
  20. >
  21. {{ item.hotSearchTitle }}
  22. </span>
  23. <span class="cell-heat">{{ formatHeat(item.hotSearchHeat) }}</span>
  24. </div>
  25. </div>
  26. </el-card>
  27. </template>
  28. <script>
  29. import apiService from "@/config/apiService.js";
  30. export default {
  31. props: {
  32. title: String,
  33. icon: String,
  34. type: String,
  35. },
  36. data() {
  37. return {
  38. hotSearchData: [],
  39. loading:false
  40. };
  41. },
  42. created() {
  43. this.fetchData(this.type);
  44. },
  45. methods: {
  46. fetchData(type) {
  47. this.loading = true
  48. apiService
  49. .get("/hotSearch/queryByType?type=" + type)
  50. .then((res) => {
  51. // 处理响应数据
  52. this.hotSearchData = res.data.data;
  53. })
  54. .catch((error) => {
  55. // 处理错误情况
  56. console.error(error);
  57. }).finally(() => {
  58. // 加载结束
  59. this.loading = false;
  60. });
  61. },
  62. getRankingClass(order) {
  63. if (order === 1) return "top-ranking-1";
  64. if (order === 2) return "top-ranking-2";
  65. if (order === 3) return "top-ranking-3";
  66. return "";
  67. },
  68. formatHeat(heat) {
  69. // 如果 heat 已经是字符串,并且以 "万" 结尾,那么直接返回
  70. if (typeof heat === "string" && heat.endsWith("万")) {
  71. return heat;
  72. }
  73. let number = parseFloat(heat); // 确保转换为数值类型进行比较
  74. if (isNaN(number)) {
  75. return heat; // 如果无法转换为数值,则原样返回
  76. }
  77. // 如果数值小于1000,直接返回该数值
  78. if (number < 1000) {
  79. return number.toString();
  80. }
  81. // 如果数值在1000到9999之间,转换为k为单位
  82. if (number >= 1000 && number < 10000) {
  83. return (number / 1000).toFixed(1) + "k";
  84. }
  85. // 如果数值大于等于10000,转换为万为单位
  86. if (number >= 10000) {
  87. return (number / 10000).toFixed(1) + "万";
  88. }
  89. },
  90. openLink(url) {
  91. if (url) {
  92. // 使用window.open在新标签页中打开链接
  93. window.open(url, "_blank");
  94. }
  95. },
  96. },
  97. };
  98. </script>
  99. <style scoped>
  100. .custom-card {
  101. background-color: #ffffff;
  102. border-radius: 10px;
  103. box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  104. margin-bottom: 20px;
  105. }
  106. .custom-card:hover {
  107. box-shadow: 0 6px 8px rgba(0, 0, 0, 0.25);
  108. }
  109. >>> .el-card__header {
  110. padding: 10px 18px;
  111. }
  112. >>> .el-card__body {
  113. display: flex;
  114. padding: 10px 0px 10px 10px;
  115. }
  116. .card-title {
  117. display: flex;
  118. align-items: center;
  119. font-weight: bold;
  120. font-size: 16px;
  121. }
  122. .card-title-icon {
  123. fill: currentColor;
  124. width: 24px;
  125. height: 24px;
  126. margin-right: 8px;
  127. }
  128. .cell-group-scrollable {
  129. max-height: 350px;
  130. overflow-y: auto;
  131. padding-right: 16px; /* 恢复内容区域的内边距 */
  132. flex: 1;
  133. }
  134. .cell-wrapper {
  135. display: flex;
  136. align-items: center;
  137. padding: 8px 8px; /* 减小上下内边距以减少间隔 */
  138. border-bottom: 1px solid #e8e8e8; /* 为每个项之间添加分割线 */
  139. }
  140. .cell-order {
  141. width: 20px;
  142. text-align: left;
  143. font-size: 16px;
  144. font-weight: 700;
  145. margin-right: 8px;
  146. color: #7a7a7a; /* 统一非特殊序号颜色 */
  147. }
  148. /* 通过在cell-heat类前面添加更多的父级选择器,提高了特异性 */
  149. .cell-heat {
  150. min-width: 50px;
  151. text-align: right;
  152. font-size: 12px;
  153. color: #7a7a7a;
  154. }
  155. .cell-title {
  156. font-size: 13px;
  157. color: #495060;
  158. line-height: 22px;
  159. flex-grow: 1;
  160. overflow: hidden;
  161. text-align: left; /* 左对齐 */
  162. text-overflow: ellipsis; /* 超出部分显示省略号 */
  163. }
  164. .top-ranking-1 .cell-order {
  165. color: #fadb14;
  166. } /* 金色 */
  167. .top-ranking-2 .cell-order {
  168. color: #a9a9a9;
  169. } /* 银色 */
  170. .top-ranking-3 .cell-order {
  171. color: #d48806;
  172. } /* 铜色 */
  173. /* 新增的.hover-effect类用于标题的hover状态 */
  174. .cell-title.hover-effect {
  175. cursor: pointer; /* 鼠标悬停时显示指针形状 */
  176. transition: color 0.3s ease; /* 平滑地过渡颜色变化 */
  177. }
  178. /* 当鼠标悬停在带有.hover-effect类的元素上时改变颜色 */
  179. .cell-title.hover-effect:hover {
  180. color: #409eff; /* 或者使用你喜欢的颜色 */
  181. }
  182. </style>

在App.vue中添加热搜组件,由于不止一个热搜,我把它做成了一个数组

  1. <template>
  2. <div id="app">
  3. <el-row :gutter="10">
  4. <el-col :span="6" v-for="(board, index) in hotBoards" :key="index">
  5. <hot-search-board
  6. :title="board.title"
  7. :icon="board.icon"
  8. :fetch-url="board.fetchUrl"
  9. :type="board.type"
  10. />
  11. </el-col>
  12. </el-row>
  13. </div>
  14. </template>
  15. <script>
  16. import HotSearchBoard from "@/components/HotSearchBoard.vue";
  17. export default {
  18. name: "App",
  19. components: {
  20. HotSearchBoard,
  21. },
  22. data() {
  23. return {
  24. hotBoards: [
  25. {
  26. title: "百度",
  27. icon: require("@/assets/icons/baidu-icon.svg"),
  28. type: "baidu",
  29. },
  30. {
  31. title: "抖音",
  32. icon: require("@/assets/icons/douyin-icon.svg"),
  33. type: "douyin",
  34. },
  35. ],
  36. };
  37. },
  38. };
  39. </script>
  40. <style>
  41. #app {
  42. font-family: Avenir, Helvetica, Arial, sans-serif;
  43. -webkit-font-smoothing: antialiased;
  44. -moz-osx-font-smoothing: grayscale;
  45. text-align: center;
  46. color: #2c3e50;
  47. margin-top: 60px;
  48. background: #f8f9fa; /* 提供一个柔和的背景色 */
  49. min-height: 100vh; /* 使用视口高度确保填满整个屏幕 */
  50. padding: 0; /* 保持整体布局紧凑,无额外内边距 */
  51. }
  52. </style>

最终的项目结构和文件如下

代码不难,无非就是使用卡片和列表对热搜进行展示,还有就是我加了一些样式,比如前三名的排序有颜色,字体改了改。

四、小结一下

在本篇文章中,我主要展示前端代码逻辑。至于后端,也做了一些更新,比如新增了queryType接口和跨域请求的处理,但这些内容都是基础的,你下载代码后就能一目了然,不懂的评论区交流,或者加我微信:hb1766435296。之前的准备工作终于开始见到成效,虽然看起来简单,但实际上解决了不少复杂问题。现在,服务器、前端和后端的基础都打好了,接下来我会继续开发,增加更多功能。

关于爬虫部分,我已经成功实现了针对12个不同网站的爬取功能。考虑到爬虫的逻辑相对简单,无需单独撰写文章来详细说明。因此,我计划在每篇文章的附录或额外部分简要介绍各个热搜网站的爬虫逻辑。这样的安排既能保证信息的完整性,又不会让文章显得过于冗长。

番外:知乎热搜爬虫

1. 爬虫方案评估

知乎热搜是这样的, 接口是:https://www.zhihu.com/api/v3/feed/topstory/hot-lists/total

数据还算完备,有标题、热度、封面、排序等,知乎的热搜接口返回的数据格式是JSON,这种比返回HTML更简单。

2. 网页解析代码

这个就可以使用Postman生成调用代码,流程我就不赘述了,直接上代码,ZhihuHotSearchJob:

  1. package com.summo.sbmy.job.zhihu;
  2. import java.io.IOException;
  3. import java.util.List;
  4. import com.alibaba.fastjson.JSONArray;
  5. import com.alibaba.fastjson.JSONObject;
  6. import com.google.common.collect.Lists;
  7. import com.summo.sbmy.dao.entity.SbmyHotSearchDO;
  8. import com.summo.sbmy.service.SbmyHotSearchService;
  9. import lombok.extern.slf4j.Slf4j;
  10. import okhttp3.OkHttpClient;
  11. import okhttp3.Request;
  12. import okhttp3.Response;
  13. import org.springframework.beans.factory.annotation.Autowired;
  14. import org.springframework.scheduling.annotation.Scheduled;
  15. import org.springframework.stereotype.Component;
  16. import static com.summo.sbmy.common.enums.HotSearchEnum.ZHIHU;
  17. /**
  18. * @author summo
  19. * @version DouyinHotSearchJob.java, 1.0.0
  20. * @description 知乎热搜Java爬虫代码
  21. * @date 2024年08月09
  22. */
  23. @Component
  24. @Slf4j
  25. public class ZhihuHotSearchJob {
  26. @Autowired
  27. private SbmyHotSearchService sbmyHotSearchService;
  28. /**
  29. * 定时触发爬虫方法,1个小时执行一次
  30. */
  31. @Scheduled(fixedRate = 1000 * 60 * 60)
  32. public void hotSearch() throws IOException {
  33. try {
  34. //查询知乎热搜数据
  35. OkHttpClient client = new OkHttpClient().newBuilder().build();
  36. Request request = new Request.Builder().url("https://www.zhihu.com/api/v3/feed/topstory/hot-lists/total")
  37. .method("GET", null).build();
  38. Response response = client.newCall(request).execute();
  39. JSONObject jsonObject = JSONObject.parseObject(response.body().string());
  40. JSONArray array = jsonObject.getJSONArray("data");
  41. List<SbmyHotSearchDO> sbmyHotSearchDOList = Lists.newArrayList();
  42. for (int i = 0, len = array.size(); i < len; i++) {
  43. //获取知乎热搜信息
  44. JSONObject object = (JSONObject)array.get(i);
  45. JSONObject target = object.getJSONObject("target");
  46. //构建热搜信息榜
  47. SbmyHotSearchDO sbmyHotSearchDO = SbmyHotSearchDO.builder().hotSearchResource(ZHIHU.getCode()).build();
  48. //设置知乎三方ID
  49. sbmyHotSearchDO.setHotSearchId(target.getString("id"));
  50. //设置文章连接
  51. sbmyHotSearchDO.setHotSearchUrl("https://www.zhihu.com/question/" + sbmyHotSearchDO.getHotSearchId());
  52. //设置文章标题
  53. sbmyHotSearchDO.setHotSearchTitle(target.getString("title"));
  54. //设置作者名称
  55. sbmyHotSearchDO.setHotSearchAuthor(target.getJSONObject("author").getString("name"));
  56. //设置作者头像
  57. sbmyHotSearchDO.setHotSearchAuthorAvatar(target.getJSONObject("author").getString("avatar_url"));
  58. //设置文章摘要
  59. sbmyHotSearchDO.setHotSearchExcerpt(target.getString("excerpt"));
  60. //设置热搜热度
  61. sbmyHotSearchDO.setHotSearchHeat(object.getString("detail_text").replace("热度", ""));
  62. //按顺序排名
  63. sbmyHotSearchDO.setHotSearchOrder(i + 1);
  64. sbmyHotSearchDOList.add(sbmyHotSearchDO);
  65. }
  66. //数据持久化
  67. sbmyHotSearchService.saveCache2DB(sbmyHotSearchDOList);
  68. } catch (IOException e) {
  69. log.error("获取知乎数据异常", e);
  70. }
  71. }
  72. }

知乎的热搜数据是自带唯一ID的,不需要我们手动生成,非常方便。

原文链接:https://www.cnblogs.com/wlovet/p/18376100

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号