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就跑起來了,效果圖如下: