安装 axios
npm install axios --save-dev
main.js
中的Vue.config.productionTip = false
设置false
以阻止 vue 在启动时产生提示。
然后再main.js
中引入,import axios from 'axios'
,然后再Vue实例对象中进行注册,
//实例化vue对象 new Vue({ router, store, axios, render: h => h(App) }).$mount('#app')
这样在其他组件还不能直接使用,而且还不能用 user 方法,需要在 vue 的原型属性添加一个属性$axios
,并且将这个属性指向 axios ,这样在其他组件我们就可以直接使用 axios 命令了。
vue 的原型属性添加一个属性 `$axios` Vue.prototype.$axios = axios
.$axios
有一个 get 方法,还有一个 post 方法,
语法是:
**get() 方法** getApi(){ this.$axios.get('rul') .then((res) => { }) .catch((err) => { }) } **post() 方法** this.$axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (res) { console.log(res); }) .catch(function (err) { console.log(err); });
.then()
方法建议使用箭头函数,如果用function
会涉及到 this 的指向问题,