vue如何根据ip地址获取实时当地城市、时间、天气
// 分
minute: ‘’,
// 月
month: ‘’,
// 日
date: ‘’,
// 星期几
day: ‘’,
// 出勤率echart数据
},
}
}
在methods中定义获取城市的方法getLocalCity,在created()中调用
getLocalCity() {
var data = {
key: ‘KSPBZ-V5L33-5EM3D-35N5X-DIY66-CRF7J’, //申请的密钥,写死就行
}
data.output = ‘jsonp’
this.$jsonp(url, data)
.then((res) => {
this.local.city = res.result.ad_info.city
// 根据城市,获取当前天气和时间(在此先预留获取天气方法,完成后取消注释)
// this.getLocalWeather(this.local.city)
return res
})
.catch((error) => {
console.log(error)
})
},
[](()2.根据获取的城市名称获取当地天气
================================================================================
[](()2.1引入axios
安装axios
npm install axios
在main.js中引入axios
import axios from “axios”;
Vue.prototype.$axios = axios; //此处根据项目情况来配置
[](()2.2使用接口,获取当地天气
[](()2.2.1声明定时器
在data中声明定时器,用于后期的销毁
timeId: ‘’,
[](()2.2.2使用接口获取实时天气数据
// 获取当地时间和天气
getLocalWeather(city) {
if (city && city !== ‘’) {
this.$axios
.get(‘http://wthrcdn.etouch.cn/weather_mini?city=’ + city)
.then((res) => {
// 获取当天数据
let todayWeather = res.data.forecast[0]
if (todayWeather !== ‘’) {
// 获取温度,取平均值
let high = todayWeather.high.split(’ )[1].slice(0, -1)
let low = todayWeather.low.split(’ )[1].slice(0, -1)
this.local.temperature = (parseInt(low) + parseInt(high)) / 2
// 获取天气类型
this.local.type = todayWeather.type
// 获取星期几
this.local.day = todayWeather.date.slice(-3)
// 获取当前时间
let newDate = new Date()
this.local.hour = newDate.getHours()
this.local.minute = newDate.getMinutes()
this.local.month = newDate.getMonth() + 1
this.local.date = newDate.getDate()
// 使用定时器,实时刷新城市、天气和时间
this.timeId = setTimeout(() => {
this.getLocalCity(city)
}, 1000)
}
})
.catch(function(error) {
console.log(error)
})
}
},
很多时候人们会使用setInterval进行时间等实时数据的刷新,但是第一次执行需要setInterval的时间间隔,会造成用户的体验感下降。因此这里使用了setTimeout进行优化,每次在执行完成后再次进行调用
[](()2.2.3销毁定时器
beforeDestroy() {
if (this.timeId && this.timeId !== ‘’) {
clearTimeout(this.timeId)
this.timeId = null
}
},
[](()3.补充
===================================================================
因为返回的时间数据为一位数时,前面不会自动补0,因此可以定义一个时间规范管道:
/**
-
处理月、日、时、分、秒等时间为个位数的情况 @param {String} string
*/
export function handleTime(time) {
