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);
      });
  }
}
相关推荐
咪库咪库咪21 小时前
vue3-组件
vue.js
10share21 小时前
100行代码 模拟实现Vue 响应式系统
前端·vue.js
用户4099322502121 天前
Vue状态管理入门第四章:组合式store和SSR风险
前端·vue.js·后端
锋行天下2 天前
半秒开!还有谁!!!
前端·vue.js·架构
JING小白2 天前
Day 1 重学Vue:响应式系统的“底层逻辑”变更,Vue2旧时代的终结与Vue3新时代的开启
前端·vue.js
OpenTiny社区2 天前
从零开发 AI 聊天页要两周?试试这款 Vue3 垂直对话组件库 TinyRobot,直接开箱即用
前端·vue.js·github
Cobyte2 天前
22.Vue Vapor 组件 props 的实现
前端·javascript·vue.js
白雾茫茫丶2 天前
探索 Nuxt.js 全栈能力:用 Better-Auth 打造类型安全的 RBAC 权限系统
前端·vue.js·nuxt.js
向阳而生6602 天前
文件上传也能玩出花?Vue3 教你优雅实现“选择文件”和“选择文件夹”🚀
vue.js
3630458412 天前
Signal 带来的架构问题思考
前端·vue.js