其中部分知识不必深究,了解会用即可。
- ES6: Promise
- ES7: async和await
- http协议
- ajax
1、axios官网:http://www.axios-js.com/
2、axios官网中文文档:http://www.axios-js.com/zh-cn/docs/
3、什么是 axios?
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
4、特性
- 从浏览器中创建 XMLHttpRequests
- 从 node.js 创建 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求数据和响应数据
- 取消请求
- 自动转换 JSON 数据
- 客户端支持防御 XSRF
1)执行Get
请求
// 为给定 ID 的 user 创建请求 axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // 上面的请求也可以这样做 axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
2)执行Post
请求
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
更多语法可以去参考官网文档。
1)由于我们目前还没有搭建自己的服务器端,所以在此通过调用阿里云的免费api获取天气预报数据显示
2)注册阿里云账号,然后访问https://market.aliyun.com/products/57126001/cmapi014123.html#sku=yuncode812300000购买免费体验套餐。
3)购买后在控制台已购买服务中心可以查看对应的AppKey、 AppSecret、AppCode(重要,需要保密)
3、使用HBuildX新建vue-cli项目,名为weather
,过程在此不再赘述,如果不会,请参考Vue系列入门教程(7)——实现简单轮播图
4、为weather
安装axios
,这里我们使用npm
安装方式,打开项目终端,使用如下指令(安装好的axios在node_modules中):
npm install axios
5、新建Weather.vue
组件(其中具体的参数含义,api使用方法参考api文档,注意替换你的APPCODE)
<template> <div> <h1>{{title}}</h1> <!-- 简便起见,我们就只显示3个数据 --> 日期:{{f2.day}} 白天天气:{{f2.day_weather}} 白天温度:{{f2.day_air_temperature}} </div> </template> <script> // 导入axios import axios from 'axios' //导出 export default { name:"Weather", data(){ return { title:"淮安明天的天气预报", // 明天天气状况封装成对象,注意要与响应中的f2属性名称保持一致 f2:{ day:"", day_weather:"", day_air_temperature:'' } } }, methods:{ getWeather(){ // 发送get请求,请求地址和参数参考阿里云文档 axios.get("http://saweather.market.alicloudapi.com/area-to-weather",{ // 文档要求请求头带Authorization认证 headers:{Authorization:'APPCODE 你的APPCODE'}, // 地区参数-支持的地区参考文档 params: { area:'淮安' } }).then(response=>{ // 使用箭头函数否则this访问不到data // 打印响应查看返回的json数据结构 console.log(response); // 获取明天的数据并赋值 this.f2 = response.data.showapi_res_body.f2; }) } }, // 生命周期方法-模板或el对应的html渲染完成后再调用里面的方法 mounted(){ this.getWeather(); } } </script> <style scoped> </style>
6、在App.vue
中导入、注册、使用
<template> <div id="app"> <Weather></Weather> </div> </template> <script> import Weather from './components/Weather.vue' export default { name: 'app', components: { Weather } } </script> <style> </style>
以上的代码可以优化,我们现在优化下代码结构。
1,、在src目录下新建services
目录,提取出一些方法与配置,方便复用
2、AppCode和请求地址都是常量,多出可能会用到,我们可以将其放到一个配置文件中,我们在services
目录下新建config.js
文件,内容如下:
// 导出AppCode export var AppCode='你的APPCODE' export var SevenDayUrl='http://saweather.market.alicloudapi.com/area-to-weather'
3、在services
目录新建weatherService.js
,内容如下:
// 导入axios和AppCode import axios from 'axios' import {AppCode} from './config.js' import {SevenDayUrl} from './config.js' // 导出根据地区获取明天天气的方法 export async function getWeather(area){ //发送请求 使用await等待响应同时方法上要加上async表示异步 var response = await axios.get(SevenDayUrl,{ // 文档要求请求头带Authorization认证 使用ES6模板字符串拼接 headers:{Authorization:`APPCODE ${AppCode}`}, // 地区参数-支持的地区参考文档 params: { area } }); // 返回明天天气数据 return response.data.showapi_res_body.f2; }
4、修改Weather.vue
如下:
一般而言,调用weatherService.js中的方法有两种方式,这里我们用两种方式实现Weather.vue,任选一种即可:
1)第一种:使用then
<template> <div> <h1>{{title}}</h1> <!-- 简便起见,我们就只显示3个数据 --> 日期:{{f2.day}} 白天天气:{{f2.day_weather}} 白天温度:{{f2.day_air_temperature}} </div> </template> <script> // 导入weatherService.js import {getWeather} from '../services/weatherService.js' //导出 export default { name:"Weather", data(){ return { title:"淮安明天的天气预报", f2:{ day:"", day_weather:"", day_air_temperature:'' } } }, // 生命周期方法-模板或el对应的html渲染完成后再调用里面的方法 mounted(){ getWeather('淮安').then(response=>{ // 使用箭头函数否则this访问不到data // 打印响应查看返回的json数据结构 console.log(response); // 获取明天的数据 this.f2 = response; }); } } </script> <style scoped> </style>
2)第二种:使用async和await
<template> <div> <h1>{{title}}</h1> <!-- 简便起见,我们就只显示3个数据 --> 日期:{{f2.day}} 白天天气:{{f2.day_weather}} 白天温度:{{f2.day_air_temperature}} </div> </template> <script> // 导入weather.js import {getWeather} from '../services/weatherService.js' //导出 export default { name:"Weather", data(){ return { title:"淮安明天的天气预报", f2:{ day:"", day_weather:"", day_air_temperature:'' } } }, async mounted(){ //模板或el对应的html渲染完成后再调用里面的方法 var response = await getWeather('淮安'); // 使用箭头函数否则this访问不到data // 打印响应查看返回的json数据结构 console.log(response); // 获取明天的数据 this.f2 = response; } } </script> <style scoped> </style>
5、运行至浏览器,测试效果与上面一样