vue数据请求

本文深入探讨了Vue框架下的数据请求方法,对比了axios和fetch两种主流请求方式的特点和使用场景,详细讲解了get、post等请求类型的具体实现,以及如何在Vue中统一配置和使用axios。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue数据请求

使用vue框架后,数据请求基本不会使用原生Ajax。
因为Ajax不符合模块化思想。

两个数据请求方案[ 二选一 ]

  1. 第三方模块: axios
    Vue中可以统一对axios进行挂载
    Vue.prototype.$http = axios
  2. 原生js提供: fetch

axios

  1. axios 是一个基于promise的HTTP库,可以用在浏览器和 node.js 中。
  2. axios的返回值是一个封装对象,可以提高安全性
  3. axios使用
    • 模拟数据请求
    • 后端接口请求
      • get
      • post
        • json
        • 表单提交
      • puta
      • delete
  4. baseURL 连接后端接口的地址
    例如axios.defaults.baseURL = 'http://xxxxx'

axios -> get请求

put,delete请求和get请求一致

axios.get(url,options)

axios({
  url:'/',
  method:'get'  //默认就是get 可以省略
  params:{  //get请求携带参数使用params
    a,
    b
  }
}).then(res => console.log(res))
 .catch(err => console.log(err))

axios -> post请求

  1. 使用application/json来发送请求
axios({
  // 发送用户名密码请求
  url: '/users',
  method: 'POST',
  data: {   //post请求携带参数使用data
    username,
    password,
    token: ''
  }
}).then(res => console.log(res))
.catch(err => console.log(err))
  1. 使用application/x-www-form-urlencoded来发送请求
// 同样发送用户名密码
const p = new URLSearchParams() // 得到数据参数携带对象
// 使用append方法来进行数据的传输
p.append('username', username)
p.append('password', password)
axios({
  url: '/users',
  method: 'POST',
  data: p  //携带数据使用依旧data
}).then(res => console.log(res))
.catch(err => console.log(err))

fetch

  1. 原生JS提供,可以说Ajax封装版本,用起来简易
  2. 符合模块化思想
  3. 在浏览器中呈现的fetch字样
  4. fetch也是promise
  5. fetch返回值是没有进过封装的,安全度比axios要低

方法:fetch( url,options )

fetch -> get请求

fetch('/',{  //fetch的参数只能连接在地址后面
  method:'GET'
}).then( data => data.json() )  //数据格式化 json()  text()   blob() 二进制格式化
  .then( res => console.log(res))  //res就是得到的真正的数据
  .catch( err => console.log(err))

fetch -> post请求

// application/x-www-form-urlencoded 提交
post () {
  fetch(`/users`,{
    method: 'POST',
    headers: new Headers({
      'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式为表单提交
    }),
    body: new URLSearchParams([["username", 'xiaoming'],["password", 123]]).toString() // 这里是请求对象
    })
    .then( data => data.json() ) // 数据格式化    json()  text()   blob() 二进制格式化
    .then( res => console.log( res )) // res就是得到的真正的数据
    .catch( err => console.log( err ))
    }
//application/json  提交

postJSON () {
  fetch(`${ baseURL }/users`, {
    method: 'POST', // or 'PUT'
    body: JSON.stringify({
      username: '小明',
      password: 123
    }), // data can be `string` or {object}!
    headers: new Headers({
      'Content-Type': 'application/json'
    })
  }).then(res => res.json())
    .catch(error => console.error('Error:', error))
    .then(response => console.log('Success:', response));
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值