1. xhr
- 不常用(太麻烦),一般进行二次封装,或者使用成型的第三方封装jQuery,axios等。axios和jQuery都是对xhr的封装。
2. jQuery
- 核心是封装Dom操作,80%的内容都是关于Dom的,Vue和React的使用是为了减少自己进行dom操作,所以没有必要引入jQuery, 多数且推荐使用axios。
3. axios
- 是promise风格的, 并且支持请求拦截件,和响应拦截器,体积小(大约是jQuery的1/4的体积),Vue和React项目中常用。
- 安装:
npm i axios
- 使用:
import axios from 'axios'
| <template> |
| <div> |
| <button @click="getStudents">获取学生信息</button> |
| </div> |
| </template> |
| |
| <script> |
| import axios from 'axios' |
| export default { |
| name:'App', |
| methods: { |
| getStudents(){ |
| axios.get('http://localhost:8080/students').then( |
| response => { |
| console.log('请求成功了',response.data) |
| }, |
| error => { |
| console.log('请求失败了',error.message) |
| } |
| ) |
| }, |
| |
| }, |
| } |
| </script> |
| |
复制
4. fetch
- 和xhr平级,都是js中内置的,可以直接使用的,也是promise风格的,缺点:返回数据会被包2层promise,得2次then才能拿到数据,最致命的是他的兼容性问题,不兼容IE浏览器,所以还是推荐axios。
5. vue-resource
- vue-resource早期Vue1.0时候使用较多,是Vue团队维护,后面交给了其他团队在维护,是Vue的一个插件库,也是对xhr的封装。目前维护的频率不高,所有还是推荐使用axios。
- 安装:
npm i vue-rsource
- 使用:在main.js中引入和使用插件,然后全局可以使用
this.$http.
| |
| import Vue from 'vue' |
| |
| import App from './App.vue' |
| |
| import vueResource from 'vue-resource' |
| |
| Vue.config.productionTip = false |
| |
| Vue.use(vueResource) |
| |
| |
| new Vue({ |
| el:'#app', |
| render: h => h(App), |
| beforeCreate() { |
| Vue.prototype.$bus = this |
| }, |
| }) |
复制

| <template> |
| <div> |
| <button @click="getStudents">获取学生信息</button> |
| </div> |
| </template> |
| |
| <script> |
| export default { |
| name:'App', |
| methods: { |
| getStudents(){ |
| this.$http.get('http://localhost:8080/students').then( |
| response => { |
| console.log('请求成功了',response.data) |
| }, |
| error => { |
| console.log('请求失败了',error.message) |
| } |
| ) |
| }, |
| |
| }, |
| } |
| </script> |
复制