官網:https://www.kancloud.cn/yunye/axios/234845vue
axios使用:jquery
main.jsios
//引入axios
import Axios from 'axios'
//將axios掛載到 Vue原型上
Vue.prototype.$https = Axios
//設置公共的url
Axios.defaults.baseURL = 'https://www.xxx.com/api/v1/';
Home.vueajax
methods:{
//獲取 分類列表的數據
getCategoryList(){
this.$https.get('course_sub/category/list/')
.then((res)=>{
console.log(res);
var data = res.data;
if(data.error_no === 0){
this.categoryList = data.data;
let obj = {
id:0,
name:'所有',
category:0
}
this.categoryList.unshift(obj);
// 數組 刪除任意一個指定的元素
//指定數組中的索引 刪除指定的元素 數組.splice(起始位置,刪除的個數)
}
})
.catch((err)=>{
console.log('獲取列表失敗',err)
})
},
可是一般我將全部的請求都放在restful的api.js下,這樣也方便後期維護vuex
api.jsnpm
import Axios from 'axios'
//設置公共的url
Axios.defaults.baseURL = '公共url';
const categoryListUrl = '/course_sub/category/list/';
const courseListUrl = '/courses/?sub_category=';
const courseDetailUrl ='/coursedetail/?courseid=';
//請求1
export function categoryList(){
return Axios.get(categoryListUrl).then(res=>res.data)
}
//請求2
export function courseList(categoryId){
return Axios.get(`${courseListUrl}${categoryId}`).then(res=>res.data)
}
//請求3
export function courseDetail(courseId){
return Axios.get(`${courseDetailUrl}${courseId}`).then(res=>res.data)
main.jsaxios
//引入axios
import Axios from 'axios'
import * as api from './restful/api'
//將axios掛載到api上
Vue.prototype.$https = api;
vue中的請求api
ajaxsent(num = 0) {
//對應api中的相應的請求
this.$https.courseList(num)
.then((res) => {
if (res.error_no === 0) {
this.msg = res.data;
this.msg.forEach((element, index) => {
element.colorName = this.colorList[index]
})
}
})
.catch((err) => {
console.log('獲取列表失敗', err)
});
this.index_id = num
},
下載數組
npm i vuex -S
restful
main.js
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state:{
num:1,
questionList:[]
},
mutations:{
setMutaNum(state,val){
console.log(val)
state.num+=val
},
setMutaAsync:function(state,val){
state.num+=val
},
course_questions(state,data){
state.questionList = data;
}
},
actions:{
setActionNum(context,val){
//Action 提交的是 mutation,而不是直接變動狀態。
context.commit('setMutaNum',val)
},
setActionAsync:function(context,val){
setTimeout(()=>{
context.commit('setMutaAsync',val)
},1)
},
course_questions(context,courseId){
//異步 aixos 異步
Axios.get(`course_questions/?course_id=${courseId}`)
.then((res)=>{
console.log(res)
let data = res.data.data;
context.commit('course_questions',data)
})
.catch((err)=>{
console.log(err)
})
}
}
})
xx.vue
export default {
name:"CourseDetail",
created(){
console.log(this.$route.params.courseId)
this.$store.dispatch('course_questions',this.$route.params.courseId)
},
computed:{
questionList(){
return this.$store.state.questionList
}
}
}