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