首页 前端知识 xhr、jQuery、axios、fetch、vue-resource简单了解和对比

xhr、jQuery、axios、fetch、vue-resource简单了解和对比

2024-02-23 11:02:11 前端知识 前端哥 224 806 我要收藏

1. xhr

  1. 不常用(太麻烦),一般进行二次封装,或者使用成型的第三方封装jQuery,axios等。axios和jQuery都是对xhr的封装。

2. jQuery

  1. 核心是封装Dom操作,80%的内容都是关于Dom的,Vue和React的使用是为了减少自己进行dom操作,所以没有必要引入jQuery, 多数且推荐使用axios。

3. axios

  1. 是promise风格的, 并且支持请求拦截件,和响应拦截器,体积小(大约是jQuery的1/4的体积),Vue和React项目中常用。
  2. 安装:npm i axios
  3. 使用: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

  1. 和xhr平级,都是js中内置的,可以直接使用的,也是promise风格的,缺点:返回数据会被包2层promise,得2次then才能拿到数据,最致命的是他的兼容性问题,不兼容IE浏览器,所以还是推荐axios。

5. vue-resource

  1. vue-resource早期Vue1.0时候使用较多,是Vue团队维护,后面交给了其他团队在维护,是Vue的一个插件库,也是对xhr的封装。目前维护的频率不高,所有还是推荐使用axios。
  2. 安装:npm i vue-rsource
  3. 使用:在main.js中引入和使用插件,然后全局可以使用this.$http.
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入插件
import vueResource from 'vue-resource'
//关闭Vue的生产提示
Vue.config.productionTip = false
//使用插件
Vue.use(vueResource)
//创建vm
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>
复制
转载请注明出处或者链接地址:https://www.qianduange.cn//article/2569.html
标签
评论
还可以输入200
共0条数据,当前/页
发布的文章

安装Nodejs后,npm无法使用

2024-11-30 11:11:38

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!