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);
      });
  }
}
相关推荐
farerboy5 小时前
WEB 项目如何禁用 F12 等功能
前端·vue.js·架构
parade岁月5 小时前
vtable-guild 被收录进 vuejs/awesome-vue 了 🎉
前端·vue.js
沙蒿同学5 小时前
一个人做完一套企业级系统,赚到了第一个 1000 块
vue.js·后端·go
mldong6 小时前
管理后台数据国际化:不建翻译表、一列 JSON、后端零改动
vue.js
Eric的技术杂货铺6 小时前
YsTable 使用:字典管理主从表页面完整实现(列配置、查询、权限按钮、主从联动、增删改查)
前端·vue.js
易朵朵6 小时前
package.json 中的 `vue-router` 详解
前端·vue.js
CopyCode6 小时前
ref、reactive、toRefs 到底该用哪个?我把三个反例都写了一遍
前端·vue.js
用户42528244567506 小时前
Vue3 复杂页面状态怎么管?别什么都往 Pinia 里塞了!
vue.js
牧艺6 小时前
cos-design 4.0:91 个特效组件一次捅成 React / Vue / Web Components / Core
前端·vue.js·web components
ikun_文6 小时前
Vue3框架项目初始化
vue.js·element·vue-router