Jquery、Vue 、Ajax、axios、Fetch区别

Jquery、Vue



jQuery Ajax 与 Vue 中 Axios 的对比


csharp 复制代码
## Ajax (get请求)
$.ajax({
  url: '/api/data',
  method: 'GET',
  success: function(response) {
    console.log(response);
  },
  error: function(error) {
    console.error(error);
  }
});
## promise风格的Axios 
#   axios get请求
axios.get('/api/data')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });
## Ajax  post请求
$.ajax({
  url: '/api/data',
  method: 'POST',
  data: { name: 'John', age: 30 },
  success: function(response) {
    console.log(response);
  }
});
## axios post 请求
axios.post('/api/data', { name: 'John', age: 30 })
  .then(response => {
    console.log(response.data);
  });

Axios 独有的拦截器功能,类似于.Core 中的中间件

csharp 复制代码
// 请求拦截器
axios.interceptors.request.use(config => {
  // 在发送请求前做些什么
  config.headers.Authorization = 'Bearer token';
  return config;
});

// 响应拦截器
axios.interceptors.response.use(
  response => {
    // 对响应数据做点什么
    return response;
  },
  error => {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);


const source = axios.CancelToken.source();

axios.get('/api/data', {
  cancelToken: source.token
}).catch(thrown => {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // 处理其他错误
  }
});

// 取消请求
source.cancel('Operation canceled by the user.');
csharp 复制代码
##  在Vue中使用
// 通常在 main.js 中全局配置
import axios from 'axios';

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

// 在组件中使用
export default {
  data() {
    return {
      users: []
    }
  },
  created() {
    axios.get('/users')
      .then(response => {
        this.users = response.data;
      })
      .catch(error => {
        console.error(error);
      });
  }
}
相关推荐
像我这样帅的人丶你还1 天前
别再让JS耽误你进步了。
css·vue.js
@yanyu6661 天前
07-引入element布局及spring boot完善后端
javascript·vue.js·spring boot
王霸天1 天前
💥别再抄网上的Scale缩放代码了!50行源码教你写一个永不翻车的大屏适配
前端·vue.js·数据可视化
悟空瞎说1 天前
深入 Vue3 响应式:为什么有的要加.value,有的不用?从设计到源码彻底讲透
前端·vue.js
SuperEugene1 天前
前端通用基础组件设计:按钮/输入框/弹窗,统一设计标准|组件化设计基础篇
前端·javascript·vue.js·架构
我命由我123451 天前
在 React 项目中,可以执行 npm start 命令,但是,无法执行 npm build 命令
前端·javascript·vue.js·react.js·前端框架·json·ecmascript
aidou13141 天前
Vue3自定义实现日期选择器(可单选或多选)
前端·javascript·vue.js·日期选择器·transition
忆琳1 天前
Vue3 优雅解决单引号注入问题:自定义指令 + 全局插件双方案
vue.js·element
Ruihong1 天前
放弃 Vue3 传统 <script>!我的 VuReact 编译器做了一次清醒取舍
前端·vue.js
蜡台1 天前
IDEA LiveTemplates Vue ElementUI
前端·vue.js·elementui·idea·livetemplates