vue-cli是一個很方便的腳手架,安裝過程可按菜鳥教程
地址:http://www.runoob.com/vue2/vue-install.html
全程按著菜鳥教程走就可以了,沒有npm或者cnpm(淘寶鏡像)請去node官網(wǎng)下載安裝Node(Node自帶),剩下的看相關(guān)教程
安裝完后,進入相應(yīng)文件夾安裝axios相關(guān)依賴
(--save和-dev沒連在一起會有些小問題)
npm install axios --save-dev
在main.js中(全局)寫入
/ The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'
//axios.defaults.withCredentials=true //全局請求頭,這是比較常用的攜帶cookie
// axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest' //另一個例子
Vue.prototype.$axios = axios
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
若是只需要局部引入的話可以在相應(yīng)文件中直接引入就好了
axios使用的兩種方法(格式):
方法一:
<script>
export default {
data(){
return{
info:[]
}
},
methods:{
},
mounted(){
//get或者post , api為接口地址
this.$axios.get('api',{
params:{ //post不需要params:這部分
//請求參數(shù)
}
}).then(res => { //res是返回結(jié)果
//你的下一步操作 例:
this.info = res.data //存數(shù)據(jù)
}).catch(err => { //請求失敗就會捕獲報錯信息
//err.response可拿到服務(wù)器返回的報錯數(shù)據(jù)
})
}
}
</script>
方法二:
<script>
export default {
data(){
return{
info:[]
}
},
methods:{
},
mounted(){
//get或者post , api為接口地址
this.$axios({
method:'post',
url:'api',
data:{ //get這里應(yīng)為params
//請求參數(shù)
},
//withCredentials:true, //局部攜帶cookie
headers:{} //如果需要添加請求頭可在這寫
}).then(res => { //res是返回結(jié)果
//你的下一步操作 例:
this.info = res.data //存數(shù)據(jù)
}).catch(err => { //請求失敗就會捕獲報錯信息
//err.response可拿到服務(wù)器返回的報錯數(shù)據(jù)
})
}
}
</script>
以上是axios使用方法,安裝教程來自菜鳥