前言:
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
})
})
}