今天在项目时遇到一个需要显示实时天气需求,在自己百度学习了一番后,写下博客记载一下
-
第一步: 需要拿到实时天气的api接口
免费天气api接口
需要注意的是在注册账号后记得激活
然后拿到我们的天气接口
-
在页面中调用引入
<!-- 天气展示 -->
<span style="margin-right: 20px">
{
{
weatherData.city}}: {
{
weatherData.data[0].wea}}
<img :src="weatherImg" v-bind:style="{width:'20px',height:'20px'}">
</span>
export default {
data() {
return {
weatherData: [],
weatherImg:''
}
},
}
methods: {
//获取天气数据
getWeather () {
var _this = this;
const url = '/weather?version=v1&appid=18348836&appsecret=BL1qScYV&city=' + '南京'
this.$axios.get(url).then( (response)=> {
_this.weatherData = response.data
_this.weatherImg = 'http://tq.daodaoim.com//tianqiapi/skin/pitaya/' + response.data.data[0].wea_img + '.png'
console.log(_this.weatherData)
}).catch(() => {
})
},
}
值得注意的是 因为我是直接在项目中调用的,之前都是通过request.js调用接口; 所以这里没有全局引入axios,而且跨域问题也没有解决;
main.js文件中全局引入axios
import axios from 'axios'
Vue.prototype.$axios = axios
vue.config.js 文件中解决跨域问题(vue-cli3.0以上在vue.config.js文件中配置;2.0在config.js中配置)
module.exports = {
outputDir: 'dist',
publicPath: process.env.NODE_ENV === 'production' ? '' : '/',
lintOnSave: false,
devServer: {
proxy: {
'/api': {
target: 'http://ecs11.czxkdz.com:30090', //本地接口跨域解决
secure: false,
changOrigin: true,
},
'/weather': {
target: "https://tianqiapi.com", //天气接口跨域
pathRewrite: {
'^/weather': '/api'
},
secure: false,
changeOrigin: true,
},
}
},
}
最终效果图
后言: 一直有一个想找一个能写自己工作中遇到问题以及解决方法的博客网站,感觉一直没有随自己心意的; 希望自己以后遇到啥问题学习解决后能记录再此;之后开发项目再遇到能回来找到解决方法; 中间其实有很多问题解决没有记录,以后还是要加强记录; 在解决问题,满足需求中学习进步吧! 加油!