18.天氣小案例

1?新增帶Layout組件的頁面

直接在views文件夾下面新增weather.vue。然后隨便寫一個123,現在先讓我們頁面能跳過去先。

讓頁面能跳過去,有好幾種方法:

1、在菜單管理自己添加一個菜單,然后把菜單分配給某個角色,再把該角色分給某個人。【然而超級管理員什么時候都能看到此菜單,因為超級管理員能無視一切權限問題】

2、在路由文件(router/index.js直接寫相關路由),然后可以手動切換瀏覽器網址進入該路由。

本次例子利用使用自己添加菜單的方法,這樣比較簡單。簡單如下圖:

組件地址:默認是views目錄下面的文件

路由地址:點擊這個功能訪問的url

意思就是點擊這個路由地址可以進入這個組件

組件路徑一定要寫對,寫不對直接進不去相應的組件。路由地址可以亂寫,但是起碼也要有點“path”的樣子吧?

先隨便在weather.vue寫一句話來測試一下:

?發現頁面也出來了:

現在我們可以開始專注頁面了。?

2?專注weather業務

首先.vue文件的代碼如下:

<template><div v-loading="loading"><el-row style="margin-top: 30px;" :gutter="20"><el-col :offset="10" :span="4"><el-button type="success" @click="handleWeather">當前城市天氣</el-button></el-col></el-row><el-row :gutter="20" v-if="city.length>0"><el-col :offset="2" :span="20"><el-descriptions title="當前實時天氣"><el-descriptions-item label="當前城市">{{ city }}</el-descriptions-item><el-descriptions-item label="溫度">{{ weather.realtime.temperature }}℃</el-descriptions-item><el-descriptions-item label="風向">{{ weather.realtime.direct }}</el-descriptions-item><el-descriptions-item label="風力">{{ weather.realtime.power }}</el-descriptions-item><el-descriptions-item label="濕度">{{ weather.realtime.humidity }}%</el-descriptions-item><el-descriptions-item label="天氣狀況">{{ weather.realtime.info }}</el-descriptions-item></el-descriptions></el-col></el-row><el-row v-for="item in weather.future" :key="item.date" style="margin-top: 30px;" :gutter="20"><el-col :offset="2" :span="20"><el-descriptions :title="item.date" :column="4"><el-descriptions-item label="風向">{{ item.direct }}</el-descriptions-item><el-descriptions-item label="溫度">{{ item.temperature }}</el-descriptions-item><el-descriptions-item label="天氣情況">{{ item.weather }}</el-descriptions-item></el-descriptions></el-col></el-row></div>
</template><script>
import {getWeather} from "@/api/gzh/weather";export default {name: "weather",data() {return {loading:false,city: "",weather: {realtime: {},future: []}}},methods: {handleWeather() {this.loading=true;getWeather().then(res => {const weatherInfo = JSON.parse(res.msg);this.city = weatherInfo.result.citythis.weather.realtime = weatherInfo.result.realtimethis.weather.future = weatherInfo.result.futureconsole.log(weatherInfo)this.loading=flase;}).catch(err => {console.error(err)})}}
}
</script><style scoped></style>

然后是前端api調用代碼:

import request from "@/utils/request";
// 查詢參數列表export function getWeather() { ?return request({ ? ?url: '/getWeatherByLocalIP', ? ?method: 'get', ?})}

接下來是后端的工具類代碼:


package com.ruoyi.web.controller.gzh;import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.http.HttpUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;@RestController
public class WeatherController {@GetMapping("/getWeatherByLocalIP")public AjaxResult getWeather() throws UnsupportedEncodingException {AjaxResult result = AjaxResult.success();String localCityName = GetLocationAndIP.getLocalCityName();//調用天氣APIString encodeCity = URLEncoder.encode(localCityName, "UTF-8");System.out.println(encodeCity);String url = "http://apis.juhe.cn/simpleWeather/query?city=" + encodeCity + "&key=81fe33a6077267b2e4ae2967af47eeb7";String weatherInfo = HttpUtils.sendGet(url);result.put("msg", weatherInfo);return result;}}

然后是后端接口的代碼:


package com.ruoyi.web.controller.gzh;import org.json.JSONException;
import org.json.JSONObject;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class GetLocationAndIP {private static String readAll(BufferedReader rd) throws IOException {StringBuilder sb = new StringBuilder();int cp;while ((cp = rd.read()) != -1) {sb.append((char) cp);}return sb.toString();}public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {try (InputStream is = new URL(url).openStream()) {BufferedReader rd = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));String jsonText = readAll(rd);return new JSONObject(jsonText);}}public Map<String, Object> getAddress() {String ip = "";// 這個網址似乎不能了用了// String chinaz = "http://ip.chinaz.com";// 改用了太平洋的一個網址String chinaz = "http://whois.pconline.com.cn/";StringBuilder inputLine = new StringBuilder();String read = "";URL url = null;HttpURLConnection urlConnection = null;BufferedReader in = null;Map<String, Object> map = new HashMap<>();try {url = new URL(chinaz);urlConnection = (HttpURLConnection) url.openConnection();// 如有亂碼的,請修改相應的編碼集,這里是 gbkin = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "gbk"));while ((read = in.readLine()) != null) {inputLine.append(read).append("\r\n");}} catch (IOException e) {e.printStackTrace();} finally {if (in != null) {try {in.close();} catch (IOException e) {e.printStackTrace();}}}// 這個是之前的正則表達式,// Pattern p = Pattern.compile("\\<dd class\\=\"fz24\">(.*?)\\<\\/dd>");// 通過正則表達式匹配我們想要的內容,根據拉取的網頁內容不同,正則表達式作相應的改變Pattern p = Pattern.compile("顯示IP地址為(.*?)的位置信息");Matcher m = p.matcher(inputLine.toString());if (m.find()) {String ipstr = m.group(0);// 這里根據具體情況,來截取想要的內容ip = ipstr.substring(ipstr.indexOf("為") + 2, ipstr.indexOf("的") - 1);map.put("ip", ip);}JSONObject json = null;try {// 這里調用百度的ip定位api服務 詳見 http://api.map.baidu.com/lbsapi/cloud/ip-location-api.htmjson = readJsonFromUrl("http://api.map.baidu.com/location/ip?ak=laOQElaF53xGGBjscGtrd10nN4j1zGki&ip=" + ip);//city = (((JSONObject) ((JSONObject) json.get("content")).get("address_detail")).get("city")).toString();map.put("city", ((JSONObject) ((JSONObject) json.get("content")).get("address_detail")).get("city").toString());} catch (Exception e) {e.printStackTrace();}return map;}public static String getLocalCityName() {GetLocationAndIP getLocationANDIp = new GetLocationAndIP();Map<String, Object> map = getLocationANDIp.getAddress();String city = map.get("city").toString();return city.substring(0, city.length() - 1);}public static void main(String[] args) {GetLocationAndIP getLocationANDIp = new GetLocationAndIP();Map<String, Object> map = getLocationANDIp.getAddress();String city = map.get("city").toString();String city_1 = city.substring(0, city.length() - 1);System.out.println(city_1);}
}

由此,天氣小demo就跑起來了,效果圖如下:

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/160266.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/160266.shtml
英文地址,請注明出處:http://en.pswp.cn/news/160266.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

詳解StringBuilder和StringBuffer(區別,使用方法,含源碼講解)

目錄 一.為什么要使用StringBuilder和StringBuffer 字符串的不可變性 性能損耗 二.StringBuilder和StringBuffer StringBuffer源碼講解 使用方式 三.常用方法總結 示例&#xff1a; 四.StringBuilder和StringBuffer的區別 一.為什么要使用StringBuilder和StringBuffe…

C語言--每日五道選擇題-- Day22

第一題&#xff08;注意&#xff09; 1.下列 C 代碼中&#xff0c;不屬于未定義行為的有&#xff1a;______。 A&#xff1a;int i0; i(i); B&#xff1a;char *p"hello"; p[1]E; C&#xff1a;char *p"hello"; char ch*p; D&#xff1a;int i0; printf(&q…

Redis7--基礎篇3(持久化)

持久化介紹 官網地址&#xff1a; https://redis.io/docs/manual/persistence RDB(Redis DataBase)AOF(Append Only File)RDB AOF RDB模式(Redis DataBase) RDB 持久性以指定的時間間隔執行數據集的時間點快照。 實現類似照片記錄效果的方式&#xff0c;就是把某一時刻的數據…

計算機組成原理(萬字爆肝整理)

第一章 計算機系統概述 “較簡單&#xff0c;不做過多贅述&#xff0c;后面會詳細學到” 第一節 計算機系統層次結構 1.計算機系統的基本組成&#xff1a;硬件軟件 2.計算機硬件的基本組成&#xff1a;運算器存儲器控制器輸入設備輸出設備 3.系統軟件和應用軟件 系統軟件…

expdp導出分區表緩慢排查(Streams AQ: waiting for messages in the queue )

基本信息 單機&#xff0c;從老環境遷移到19.19。之前的導出速度接受范圍內。硬件是提升的 導出使用了壓縮&#xff0c;加密&#xff0c;并行64進程&#xff0c;表分區約90個&#xff0c;無lob字段。 現象 導出開始時能并行導出&#xff08;并行約45個&#xff0c;沒起到64…

Cypress環境變量

Cypress環境變量 baseUrl 當你配置了 baseUrl &#xff0c;測試套件中的 cy.visit() 、 cy.request() 都會自動以 baseUrl 的值作為前綴并且&#xff0c;當你需要訪問某些網址或者發起接口請求時&#xff0c;在代碼中就可以不用再指定請求的 host 或者 url 了 如何配置 base…

Java進階——多線程相關,實際應用中的積累,持續更新

目錄 多線程相關CountDownLatch賽跑的案例countDownLatch.await(300, TimeUnit.SECONDS); Java其他進階Map的put方法只放一個元素的集合 多線程相關 CountDownLatch 案例&#xff1a;主線程的執行需要等待子線程執行完&#xff0c;等各個線程執行完畢后&#xff0c;主線程做收…

redis的高可用(主從復制和哨兵模式)

redis的高可用&#xff08;主從復制和哨兵模式&#xff09; redis的性能管理&#xff1a;redis的數據緩存在內存當中 INFO memory&#xff1a;查看redis內存使用情況 used_memory:1800800&#xff1a;redis中數據占用的內存 used_memory_rss:5783552&#xff1a;redis向操作…

Halcon Solution Guide I basics(3): Region Of Interest(有興趣區域/找重點)

文章目錄 文章專欄前言文章解讀前言創建ROI案例1&#xff1a;直接截取ROI手動截取ROI 總結ROI套路獲取窗口句柄截取ROI區域獲取有效區域 Stop組合 文章專欄 Halcon開發 Halcon學習 練習項目gitee倉庫 CSDN Major 博主Halcon文章推薦 前言 今天來看第三章內容&#xff0c;既然是…

QTableWidget——編輯單元格

文章目錄 前言熟悉QTableWiget&#xff0c;通過實現單元格的合并、拆分、通過編輯界面實現表格內容及屬性的配置、實現表格的粘貼復制功能熟悉QTableWiget的屬性 一、[單元格的合并、拆分](https://blog.csdn.net/qq_15672897/article/details/134476530?spm1001.2014.3001.55…

Docker實踐筆記7:構建MySQL 8鏡像

使用Docker構建MySQL 8鏡像并運行容器 本教程將指導您使用Dockerfile構建和運行一個MySQL 8容器。讓我們開始吧&#xff01; 步驟1&#xff1a;創建Dockerfile 在您的項目根目錄下創建一個名為Dockerfile的文件。以下是Dockerfile的示例內容&#xff1a; # 基于最新的MySQL…

docker、elasticsearch8、springboot3集成備忘

目錄 一、背景 二、安裝docker 三、下載安裝elasticsearch 四、下載安裝elasticsearch-head 五、springboot集成elasticsearch 一、背景 前兩年研究了一段時間elasticsearch&#xff0c;當時也是網上找了很多資料&#xff0c;最后解決個各種問題可以在springboot上運行了…

vue-使用input封裝上傳文件圖片全局組件

前言 實際開發過程中&#xff0c;我們經常遇見需要上傳文件圖片功能&#xff0c;可以封裝一個全局組件來調用 原理很簡單&#xff0c;首先獲取到文件或圖片對象&#xff0c;調用自己公司文檔服務器的接口&#xff0c;上傳文件圖片 為了方便用戶體驗&#xff0c;我們應該在上傳…

Godot

前言 為什么要研究開源引擎 主要原因有&#xff1a; 可以享受“信創”政策的紅利&#xff0c;非常有利于承接政府項目。中美脫鉤背景下&#xff0c;國家提出了“信創”政策。這個政策的核心就是&#xff0c;核心技術上自主可控。涉及的產業包括&#xff1a;芯片、操作系統、數據…

【Django使用】md文檔10大模塊第5期:Django數據庫增刪改查和Django視圖

Django的主要目的是簡便、快速的開發數據庫驅動的網站。它強調代碼復用&#xff0c;多個組件可以很方便的以"插件"形式服務于整個框架&#xff0c;Django有許多功能強大的第三方插件&#xff0c;你甚至可以很方便的開發出自己的工具包。這使得Django具有很強的可擴展…

Vue項目 配置項設置

一、項目運行時瀏覽器自動打開 找到package.json文件 找到"sctipts"配置項 在"serve"配置項最后加上--open "scripts": {"serve": "vue-cli-service serve --open","build": "vue-cli-service build&quo…

Redis面試內容,Redis過期策略,Redis持久化方式,緩存穿透、緩存擊穿和緩存雪崩,以及解決辦法

文章目錄 一、redis什么是RedisRedis使用場景1、緩存2、數據共享[分布式](https://so.csdn.net/so/search?q分布式&spm1001.2101.3001.7020)3、分布式鎖4、全局ID5、計數器6、限流7、位統計 Redis有5中數據類型&#xff1a; SSHLZRedis中一個key的值每天12點過期&#xff…

Cookie、Session、CBV加裝飾器的三種方法

【0】cookie、session和Token的發展史 【1】Cookie的形式 存儲形式&#xff1a;k&#xff1a;v鍵值對存儲位置&#xff1a;客戶端缺點&#xff1a;不安全&#xff0c;信息可能會泄露 【2】session的形式 標識符&#xff0c;表示我是當前用戶加密出來的數據對敏感信息進行加密…

排序算法-----快速排序(非遞歸實現)

目錄 前言 快速排序 基本思路 非遞歸代碼實現 前言 很久沒跟新數據結構與算法這一欄了&#xff0c;因為數據結構與算法基本上都發布完了&#xff0c;哈哈&#xff0c;那今天我就把前面排序算法那一塊的快速排序完善一下&#xff0c;前面只發布了快速排序遞歸算法&#xff0c;…

單鏈表相關面試題--3.鏈表的中間節點

3.鏈表的中間節點 876. 鏈表的中間結點 - 力扣&#xff08;LeetCode&#xff09; /* 解題思路&#xff1a; 通過快慢指針找到中間節點&#xff0c;快指針每次走兩步&#xff0c;慢指針每次走一步&#xff0c;當快指針走到結尾的時候&#xff0c;慢指針正好走到中間位置 */ typ…