cnpm install axios -s
cnpm install vue-axios --save
main.js中:
import axios from “axios”
接口封装
在src下创建utils文件夹,在utils文件夹里创建request.js
//网路请求方法,封装
import axios from "axios";
const ajax=axios.create({//自定义axios对象
baseURL:"http://localhost:3000/",//基地址
// timeout:3000
})
export default ajax
src下创建api文件夹
index.js
import {searchurl} from '@/api/search'
export const searchurlApi=searchurl
import {playlist} from '@/api/playlist'
export const playlistApi=playlist
import {banner} from '@/api/banner'
export const bannerApi=banner
import {lyric} from '@/api/lyric'
export const lyricApi=lyric
banner.js
import request from '@/utils/request'
export const banner = params=>request({
url:"/banner",
params
})
playlist.js
import request from '@/utils/request'
export const playlist = params=>request({
url:"/playlist/track/all",
params
})
ps:最好一个页面里的axios放在一个文件夹里
在vuex中使用axios
actions: {
async getTopList(context,value){
let res=await toplistApi({})
console.log(res)
context.commit("updateTopList",res.data.list)
},
mutations: {
updateTopList(state,value){
state.TopList=value
},
}
//修改vuex中state的值
export default new Vuex.Store({
state: {
TopList:{},//分类
},
接口数据的渲染
async created() {
this.$store.dispatch('getTopList')
},
v-for="(item,index) in TopList" :key="index"