前言:
vue项目开发中一般使用axios来代替Ajax用来请求数据,其机制是通过Promise实现对Ajax的封装,axios可以从node.js创建http请求,并且支持Promise的API,相比较而言axios跟具有优势
下载(主要针对ajax的请求与json格式的数据):
npm install axios
npm install jsonp
使用:在main.js
文件中引入:
import Vue from 'vue'
improt axios from "./utils/axios"
Vue.prototype.$axios=axios //将请求模块挂载在vue原型上
在utils目录的axios文件中配置axios
引入axios:import axios from 'axios'
配置请求和响应拦截器 :
// 请求拦截器
axios.interceptors.request.use(function (config) {
// console.log('请求拦截器')
// console.log(config)
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
//响应拦截器
axios.interceptors.response.use(function (response) {
// console.log('响应拦截器')
// console.log(response)
return response.data;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
抛出模块:export default axios
配置统一管理项目的api接口(api/index.js)
引入所需依赖:
improt axios from "../utils/axios"
improt jsonp from "jsonp"
//get请求方式
export const getRecommentList=()=>{
return new Promise((resolve,reject)=>{
let url='/hehe/music/api/getDiscList'
axios.get(url)
.then((data)=>{
resolve(data)
})
.catch((err)=>{
reject(err)
})
})
}
//post方式
export const getRecommentList=()=>{
return new Promise((resolve,reject)=>{
let url='/hehe/music/api/getDiscList'
let data={
firstName: 'Fred',
lastName: 'Flintstone'
}
axios.post(url,data)
.then((response)=>{
resolve(response)
})
.catch((err)=>{
reject(err)
})
})
}
//没有经过处理的请求会产生跨域,因此需要解决跨域问题,axios有内部解决跨域方式,一般采用proxy解决
组件中使用
首先引入方法:
import {getRecommentList} from 'api/index.js'
在methods
方法中定义方法
getSongData(mid){
getSongList(mid).then((res)=>{
console.log(res) //接口请求回来的数据
this.name=res.data.singer_name //在data中定义变量来接收数据,把请求到的数据赋值给定义的变量,并渲染到页面
this.img=getAvatorUrl(res.data.singer_mid)
let tmpdata=songData(res.data.list)
getMusicUrl(tmpdata)
.then((res)=>{
console.log(res)
this.list=res
})
})
}