vue项目里访问第三方接口如天气接口、获取IP接口

5 篇文章 0 订阅

天气接口

这里用的是这个:https://www.tianqiapi.com
默认返回当前IP地区天气
在这里插入图片描述
请求接口:

  getDateWeatherAir () {
    return $http({
      url: `https://www.tianqiapi.com/参数`,
      method: 'get',
    });
  },

数据举例:
在这里插入图片描述
方法:

store.getDateWeatherAir(ip).then(res => {
        if (res) {
          this.weather.today = res.data[0];
          this.weather.tmr = res.data[1];
        }
      });

IP

获取IP地址,可以用搜狐的这个
http://pv.sohu.com/cityjson?ie=utf-8

在这里插入图片描述

1、index.html里面写script

在index.html中直接写

<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>
<script type="text/javascript">
    sessionStorage.setItem('ip', returnCitySN["cip"]);
</script>

在页面中直接取
let ip = sessionStorage.getItem('ip');
这种方法不是很推荐,会导致在每个页面都访问该外部接口

2、用js间接写。。

export default function getIP () {
  let script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'http://pv.sohu.com/cityjson?ie=utf-8';
  document.head.appendChild(script);
  let script2 = document.createElement('script');
  script2.type = 'text/javascript';
  script2.innerText = 'sessionStorage.setItem(\'ip\', returnCitySN["cip"]);';
  document.head.appendChild(script2);
}

但是容易报错returnCitySN is not defined

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值