您的位置:首页 > Web前端 > Vue.js

个人笔记-----Vue中与后台通信axios【如有不对,欢迎指正】

2019-05-02 22:23 344 查看

安装 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 的指向问题,

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐