Vue 原本有一个官方推荐的 ajax 插件 vue-resource,但是自从 Vue 更新到 2.0 之后,官方就不再更新维护 vue-resource,并推荐axios,
目前主流的 Vue 项目,都选择 axios 来完成 ajax 请求。
使用方法:
方案一:改原型
1.安装
npm install axios --save-dev
2.使用:
main.js中:
import axios from
"axios"
Vue.prototype.$ajax=axios
将 axios 改写为 Vue 的原型属性,这样其它的组件中,方可以使用 axios 命令的,(或者在要引用的组件页直接 import axios from
"axios"
)
3.方法中可以使用:
this.$ajax({
method:'get',
url:url,
data:data
}).then(function (res) {
console.log(res)
}).catch(function (err) {
console.log(err)
})
本地测试发现,url接口路径地址,用绝对路径更好点。相对地址有时候抓取报错。原因未知。
关于get,post方法:绕坑参考:http://blog.csdn.net/milli236/article/details/78053711
方案二:在 Vuex 中封装
之前的文章中用到过 Vuex 的 mutations,从结果上看,mutations 类似于事件,用于提交 Vuex 中的状态 state
action 和 mutations 也很类似,主要的区别在于,action 可以包含异步操作,而且可以通过 action 来提交 mutations
另外还有一个重要的区别:
mutations 有一个固有参数 state,接收的是 Vuex 中的 state 对象
action 也有一个固有参数 context,但是 context 是 state 的父级,包含 state、getters
Vuex 的仓库是 store.js,将 axios 引入,并在 action 添加新的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
// store.js
import Vue from
'Vue'
import Vuex from
'vuex'
// 引入 axios
import axios from
'axios'
Vue.use(Vuex)
const store =
new
Vuex.Store({
// 定义状态
state: {
test01: {
name:
'Wise Wrong'
},
test02: {
tell:
'12312345678'
}
},
actions: {
// 封装一个 ajax 方法
saveForm (context) {
axios({
method:
'post'
,
url:
'/user'
,
data: context.state.test02
})
}
}
})
export
default
store
|
注意:即使已经在 main.js 中引入了 axios,并改写了原型链,也无法在 store.js 中直接使用 $ajax 命令
换言之,这两种方案是相互独立的
在组件中发送请求的时候,需要使用 this.$store.dispatch 来分发
1
2
3
4
5
|
methods: {
submitForm () {
this
.$store.dispatch(
'saveForm'
)
}
}
|
submitForm 是绑定在组件上的一个方法,将触发 saveForm,从而通过 axios 向服务器发送请求
附:配置 axios
上面封装的方法中,使用了 axios 的三个配置项,实际上只有 url 是必须的。
为了方便,axios 还为每种方法起了别名,比如上面的 saveForm 方法等价于:
1
|
axios.post('/user', context.state.test02)
|
完整的请求还应当包括 .then 和 .catch
1
2
3
4
5
6
|
.then(function(res){
console.log(res)
})
.catch(function(err){
console.log(err)
})
|
当请求成功时,会执行 .then,否则执行 .catch
原文链接:http://www.cnblogs.com/wisewrong/p/6402183.html