axios数据请求 《3》 --fetch

本文介绍如何在Vue项目中使用Fetch API进行静态和动态数据请求,包括GET和POST方法,展示了具体的代码实现和错误处理策略。
<!-- 引入-->
  <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<!-- html部分-->
	<div id="app">
      <div class="container">
        <div class="row">
          
          <h3> 静态请求【 模拟数据  】 </h3>
            <button type="button" class="btn btn-primary" @click = "getStatic" > getJson </button>
          <h3> 动态请求 【 真实接口】 </h3>
            <button type="button" class="btn btn-primary" @click = "get"> get </button>
            <button type="button" class="btn btn-primary" @click = "post"> post </button>
        </div>
      </div>
    </div>
new Vue({
    el: '#app',
    methods: {
      getStatic () {
        //使用fetch请求mock数据

        fetch('./mock/data/data.json')
          .then( res => res.json() )  // 数据格式化 
          .then( data => console.log( data ))  // 获取数据格式化的数据
          .catch( error => console.log( error )) // 错误捕获

      },
      get () {
        //使用fetch请求动态数据  get

        fetch('http://localhost/get.php?a=1&b=2')
          .then( res => res.text() )  // 数据格式化 
          .then( data => console.log( data ))  // 获取数据格式化的数据
          .catch( error => console.log( error )) // 错误捕获

      },
      post () {
        // 使用post请求动态数据

        fetch('http://localhost/post.php', {
          method: 'POST', // or 'PUT'
          body: new URLSearchParams([['a',1],['b',2]]).toString(),
          headers: new Headers({
            'Content-Type': 'application/x-www-form-urlencoded'
          })
        }).then(res => res.text())
        .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、付费专栏及课程。

余额充值