共有三种方法:

1.结合 vue-axios使用

首先在主入口文件main.js中引用

import axios from 'axios'
import VueAxios from 'vue-axios' Vue.use(VueAxios,axios);

之后就可以在组件文件中的methods里去使用了

this.axios.get('/api/usrmng')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

2. axios 改写为 Vue 的原型属性

首先在主入口文件main.js中引用,之后挂在vue的原型链上

import axios from 'axios'
Vue.prototype.$http = axios

在组件中使用

this.$http.get('/api/usrmng')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

3.结合 Vuex的action

在vuex的仓库文件store.js中引用,使用action添加方法

import Vue from 'Vue'
import Vuex from 'vuex' import axios from 'axios' Vue.use(Vuex)
const store = new Vuex.Store({
// 定义状态
state: {
user: {
name: 'root'
}
},
actions: {
// 封装一个 ajax 方法
login (context) {
axios({
method: 'post',
url: '/user',
data: context.state.user
})
}
}
}) export default store

在组件中发送请求的时候,需要使用 this.$store.dispatch

methods: {
submitForm () {
this.$store.dispatch('login')
}
}

前端交流群,群文件提供大量文档、书籍和资料。期待你的加入!群号:127768464

最新文章

  1. .NET LINQ 元素操作
  2. shell学习三十四天----printf详解
  3. IO中同步、异步与阻塞、非阻塞的区别
  4. maven nexus-staging-maven-plugin exception-connect timed out
  5. Python语言及其应用 - 知识点遍历
  6. C++学习36 string类和字符串
  7. 基于jQuery的web在线流程图设计器GooFlow
  8. 1483:[HNOI]2009 梦幻布丁 - BZOJ
  9. ruby2.2.2在msvc2010上编译
  10. 数据挖掘之clara算法原理及实例(代码中有bug)
  11. 使用diff和patch指令生成文件差异和还原文件
  12. android TextView实现滚动显示效果
  13. 实验楼Python破解验证码
  14. vue-resources&axios
  15. Vue渲染函数
  16. AngularJS中ui-router全攻略
  17. Docker入门(CentOS7)
  18. TZOJ 4325 RMQ with Shifts(线段树查询最小,暴力更新)
  19. vi规范
  20. 对Dataguard的三种模式的理解

热门文章

  1. TR move up && TR move down
  2. java线程安全问题原理性分析
  3. angular1结合webpack构建工具
  4. linux搭建nginx图片服务器
  5. ant用法
  6. stopPropagation()阻止事件向父容器传递
  7. python 之 BeautifulSoup标签查找与信息提取
  8. 【Leetcode】【Easy】Climbing Stairs
  9. docker 部署 nginx+php+mysql
  10. June 02nd 2017 Week 22nd Friday