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.city
        this.weather.realtime = weatherInfo.result.realtime
        this.weather.future = weatherInfo.result.future
        console.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();
        //调用天气API
        String 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();
            // 如有乱码的,请修改相应的编码集,这里是 gbk
            in = 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.htm
            json = 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.mfbz.cn/a/178429.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

瑞吉外卖优化

1.缓存问题 用户数量多&#xff0c;系统访问量大频繁访问数据库,系统性能下降,用户体验差 2.导入依赖 和配置 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependenc…

线程安全

文章目录 观察线程安全问题线程安全的概念出现线程安全问题的原因共享数据原子性总结 synchronized - 锁synchronized 特性互斥可重入 synchronized 的使用修饰普通方法修饰静态方法修饰代码块 解决线程安全问题两个线程两把锁哲学家就餐问题 - N个线程M把锁解决策略 死锁成因总…

回归算法优化过程推导

假设存在一个数据集&#xff0c;包含工资、年龄及贷款额度三个维度的数据。我们需要根据这个数据集进行建模&#xff0c;从而在给定工资和年龄的情况下&#xff0c;实现对贷款额度的预测。其中&#xff0c;工资和年龄是模型构建时的两个特征&#xff0c;额度是模型输出的目标值…

【NLP】GPT 模型如何工作

介绍 2021 年&#xff0c;我使用 GPT 模型编写了最初的几行代码&#xff0c;那时我意识到文本生成已经达到了拐点。我要求 GPT-3 总结一份很长的文档&#xff0c;并尝试了几次提示。我可以看到结果比以前的模型先进得多&#xff0c;这让我对这项技术感到兴奋&#xff0c;并渴望…

Linux 磁盘/分区/修复 命令

目录 1. lsblk&#xff08;list block devices&#xff09; 2. fdisk&#xff08;fragment disk&#xff09; 3. gdisk 4. mkfs&#xff08;make filesystem&#xff09; 5. df&#xff08;display file-system disk space usage&#xff09; 6. du 7. fsck&#xff08;file-sy…

千帆Llama 2中文增强技术介绍--SFT,预训练,指令优化

目录 千帆Llama 2中文增强技术介绍 SFT&#xff0c;预训练&#xff0c;指令优化 千帆Llama 2中文增强技术介绍 SFT&#xff0c;预训练&#xff0c;指令优化

JavaScript中的继承

前言 继承 1.借用构造函数继承也叫经典继承 2.原型链继承 3.组合继承 1 2 1.经典继承 借用构造函数实现继承 // 创建父构造函数 function Animal(type,weight,age,length){this.type type;this.weight weight;this.age age;this.length length; }; Animal.prot…

一个工具让你明白“万丈高楼平地起”,拒绝重复造轮子!

大家在公司工作当中是不是很多时间装环境很麻烦&#xff0c;一个项目要上线了&#xff0c;开始网上搜了一边又一遍的环境搭建教程&#xff1f;等到下一个项目要上线了&#xff0c;又上网上搜了一边又一遍的环境搭建教程。关键天花乱坠的互联网&#xff0c;找不到很靠谱的呀。有…

Python数据分析30w人都在看

&#x1f449;博__主&#x1f448;&#xff1a;米码收割机 &#x1f449;技__能&#x1f448;&#xff1a;C/Python语言 &#x1f449;公众号&#x1f448;&#xff1a;测试开发自动化【获取源码商业合作】 &#x1f449;荣__誉&#x1f448;&#xff1a;阿里云博客专家博主、5…

深入了解Performance API:优化网页性能的利器

在现代Web开发中&#xff0c;优化网页性能是至关重要的。用户对于加载速度和交互性能的要求越来越高&#xff0c;而Performance API作为一组用于测量和监控网页性能的JavaScript接口&#xff0c;为开发者提供了丰富的工具和信息。本文将深入探讨Performance API的各个方面&…

2021年09月 Scratch(二级)真题解析#中国电子学会#全国青少年软件编程等级考试

Scratch等级考试(1~4级)全部真题・点这里 一、单选题(共25题,每题2分,共50分) 第1题 执行下图所示程序,舞台上的角色? A:在1秒内滑行到随机位置 B:不断地重复滑行到随机位置 C:只有按下空格键的时候,才会滑行到随机位置 D:只有按下空格键以外键的时候,才会滑行…

SpringMVC问题

文章目录 SpringMVC运行流程MVC的概念与请求在MVC中的执行路径&#xff0c;ResponsBody注解的用途SpringMVC启动流程 SpringMVC运行流程 • 客户端&#xff08;浏览器&#xff09;发送请求&#xff0c;直接请求到 DispatcherServlet 。 • DispatcherServlet 根据请求信息调用 …

vscode-insiders Remote-SSH XHR failed无法访问远程服务器

问题概述&#xff1a; destFolder/home/apple/.vscode-server-insiders > destFolder2/vscode-cli-05cd2640ec8a106a4ee99cb38e6ee34fbec04f11.tar.gz > 194f252f7426:trigger_server_download_end > Waiting for client to transfer server archive... > W…

C语言好好题(一维数组)

两天没有更新了&#xff0c;贴纸们&#xff0c;有没有想我呀。&#x1f604;&#x1f604;&#x1f604; 好了&#xff0c;就寒暄到这里吧&#xff0c;下面请看题&#xff1a; 有序序列判断 输入一个整数序列&#xff0c;判断是否是有序序列&#xff0c;有序&#xff0c;指序列…

Postman如何使用(一):导入导出和发送请求查看响应

一、Postman如何导入导出打包的应用 在Postman中导入导出我们的 测试数据包 和 工作环境 非常的方便&#xff1a; 导出数据包的方法如下&#xff1a; 如果你想学习自动化测试&#xff0c;我这边给你推荐一套视频&#xff0c;这个视频可以说是B站播放全网第一的自动化测试教程…

10年开发工程师总结,8大主流程序员兼职平台,月入30k不是梦!

今年互联网行业陆续裁员减薪&#xff0c;许多人怨声载道的同时也开始另谋出路。而对于程序员更是应该提早做好准备&#xff0c;活跃在兼职接单的最前沿。 我们程序员是一门技术工种&#xff0c;与互联网其他行业相比薪水会相对高一点&#xff0c;不过钱也不是那么好赚的&#…

2023-11-21 LeetCode每日一题(美化数组的最少删除数)

2023-11-21每日一题 一、题目编号 2216. 美化数组的最少删除数二、题目链接 点击跳转到题目位置 三、题目描述 给你一个下标从 0 开始的整数数组 nums &#xff0c;如果满足下述条件&#xff0c;则认为数组 nums 是一个 美丽数组 &#xff1a; nums.length 为偶数对所有满…

腾讯三季度财报解读:AI大模型成下个十年的新支点?

2023年&#xff0c;腾讯重回高增长轨道。 近日&#xff0c;腾讯披露了2023年第三季度财报&#xff0c;营收1546.25亿元&#xff0c;同比增长10%&#xff1b;非国际通用会计准则下的净利润为449.21亿元&#xff0c;同比增长39%。此前两个季度&#xff0c;腾讯的营收、净利润增速…

【西行纪年番】孙悟空对战阴界王,素衣奄奄一息,巨灵拳霸气一击

Hello,小伙伴们&#xff0c;我是拾荒君。 《西行纪年番》第20集已更新。为了救回素衣&#xff0c;孙悟空想尽办法&#xff0c;最后他拜托沙悟净帮忙&#xff0c;终于成功把自己传送到阴界。原来&#xff0c;素衣的魂魄被阴界王藏在了他制造的人偶之中。沙悟净提醒孙悟空必须在…

【LeetCode二叉树进阶题目】606,102,107

二叉树进阶题目 606. 根据二叉树创建字符串解题思路及实现 102. 二叉树的层序遍历解题思路及实现 107. 二叉树的层序遍历 II解题思路及实现 606. 根据二叉树创建字符串 描述 给你二叉树的根节点 root &#xff0c;请你采用前序遍历的方式&#xff0c;将二叉树转化为一个由括号…