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);
      });
  }
}
相关推荐
saadiya~2 小时前
Vue + WebSocket 实时数据可视化实战:多源融合与模拟数据双模式设计
vue.js·websocket·信息可视化
midsummer_woo7 小时前
基于springboot的在线教育系统(源码+论文)
vue.js·spring boot·mysql
在逃的吗喽9 小时前
黑马头条项目详解
前端·javascript·ajax
香菜狗11 小时前
vue3响应式数据(ref,reactive)详解
前端·javascript·vue.js
拾光拾趣录11 小时前
为什么我们要亲手“捏”一个 Vue 项目?
前端·vue.js·性能优化
顽疲12 小时前
从零用java实现 小红书 springboot vue uniapp(14) 集成阿里云短信验证码
java·vue.js·spring boot·阿里云·uni-app
The_era_achievs_hero12 小时前
uni-appDay02
javascript·vue.js·微信小程序·uni-app
YGY Webgis糕手之路13 小时前
OpenLayers 快速入门(六)Interaction 对象
前端·vue.js·经验分享·笔记·web
前端开发爱好者13 小时前
尤雨溪力荐 Vue-Plugins-Collection!Vue 生态 最强插件 导航!
前端·javascript·vue.js
_未完待续13 小时前
框架实战指南-透明元素
前端·vue.js