vue中數據請求的三種方法

  • 2020 年 3 月 14 日
  • 筆記

注意請求可能存在跨域問題,需要去配置好

這三種建議使用axios

1.resource

  Vue 要實現非同步載入需要使用到 vue-resource 庫。

  Vue.js 2.0 版本推薦使用 axios 來完成 ajax 請求。

  先導入一個線上cdn的地址,當然還可以去npm安裝,但個人覺得這種方便

<script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>

 

  實現GET請求

    <div id="box">          <ul>              <li v-for='item of img'><img :src='item.img' alt=""></li>          </ul>      </div>      <script>          var app = new Vue({              el: '#box',              data: {                  img: ''              },              mounted() {                  //get請求                  this.$http.get('http://localhost:3000/api/banner').then(function(res){                      this.img = res.body.data                  },function(){                      console.log('請求失敗處理');                  });              }          })      </script>

  如果需要傳遞數據,可以使用 this.$http.get(‘get.php’,{params : jsonData}) 格式,第二個參數 jsonData 就是傳到後端的數據。

  實現POST請求

<div id="box">          <ul>              <li v-for='item of img'><img :src='item.img' alt=""></li>          </ul>      </div>      <script>          var app = new Vue({              el: '#box',              data: {                  img: ''              },              mounted() {                  //post請求  需要第三個參數{emulateJSON:true}                  this.$http.get('http://localhost:3000/api/banner',{name: '王富貴'},{emulateJSON:true}).then(function(res){                      this.img = res.body.data                  },function(){                      console.log('請求失敗處理');                  });              }          })

  post 發送數據到後端,需要第三個參數 {emulateJSON:true}。

  emulateJSON 的作用: 如果Web伺服器無法處理編碼為 application/json 的請求,你可以啟用 emulateJSON 選項。

2.fetch(次方法vue自帶的不需要安裝其他)

  GET方法

  這個方法只能在地址欄傳參

//get方法  只能在地址欄傳參  fetch('http://localhost:3000/api/banner')  .then(res => {      //return 返回給上一層 ,不然下一層用不了      return res.json()  })  .then(data => {      console.log(data)  })

  POST方法

var url = 'http://localhost:3000/api/user/loging'  fetch(url, {      method: 'post',      headers: {          //這裡是需要去network裡面看          'Content-Type': 'application/x-www-form-urlencoded'      },      body: 'tel=xdd212&password=1515'  })  .then(res => {      //return 返回給上一層 ,不然下一層用不了      return res.json()  })  .then(data => {      console.log(data)  })

  另一種傳參方式

//post 另一種傳參方式  fetch(url, {      method: 'post',      headers: {          //看個人習慣          'Content-Type': 'application/json'      },      body: JSON.stringify({          tel: 'xdd212',          password: '1515'      })  })  .then(res => {      //return 返回給上一層 ,不然下一層用不了      return res.json()  })  .then(data => {      console.log(data)  })

3.axios

  Axios 是一個基於 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中

  用法和jq很類似

  安裝或者引入cdn地址   npm i axios

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

  GET請求

    <div id="box">          <ul>              <li v-for='item of img'><img :src='item.img' alt=""></li>          </ul>      </div>      <script>          var app = new Vue({              el: '#box',              data: {                  img: ''              },              mounted(){                  //需要傳參的話可以在地址欄後面拼接                  axios.get('http://localhost:3000/api/banner',                  //還可以這樣傳參                  //     {                  //         params:{                  //             name:'王富貴'                  //         }                  //     }                  )                  .then(res => {                      console.log(res)                  })              }          })      </script>

  POST請求

    <div id="box">          <ul>              <li v-for='item of img'><img :src='item.img' alt=""></li>          </ul>      </div>      <script>          var app = new Vue({              el: '#box',              data: {                  img: ''              },              mounted(){                  //需要傳參的話可以在地址欄後面拼接                  axios.post('http://localhost:3000/api/urse/loging',                       {                              age: 18                               name:'王富貴'                       }                  )                  .then(res => {                      console.log(res)                  })              }          })      </script>

  一次執行多個請求

var app = new Vue({              el: '#box',              data: {                  img: ''              },              mounted(){                  function fn1(){                      return axios.get('http://localhost:3000/api/banner')                  }                  function fn2(){                      return axios.get('http://localhost:3000/api/pro')                  }                  //注意這裡必須要使用數組                  axios.all([fn1() , fn2()])                  //函數裡面對應的數字裡面的值                  .then(axios.spread(function (fn1, fn2) {                      console.log(fn1)                  }))              }          })

  axios

  可以自己配置參數

var app = new Vue({              el: '#box',              data: {                  img: ''              },              mounted(){                  axios({                      //注意不寫請求方式的話默認是get                      method: 'post',                      url: 'http://localhost:3000/api/user/loging',                      data: {                          tel: "xdd212",                          password: "1515"                      }                  })                  .then(res => {                      console.log(res)                  })              }          })

  你可以自己定義一個axios

        //這裡創建一個自定義配置的axios          var init = axios.create({              //這裡可配置文件的長路徑              baseURL: 'http://localhost:3000/api'          })          // 假設如果很多介面都需要使用 token驗證,可以把token資訊放在請求頭          init.defaults.headers.token = '1231654984561646546565464654654646321654asdasdasd'            var app = new Vue({              el: '#box',              data: {                  img: ''              },              mounted(){                  //下面調用axios的時候就是調用我們自定義創建的                  init({                      method:'get',                      //然後到這下面可以直接寫短路徑,後期方便維護                      url: '/banner'                  })                  .then(res => {                      console.log(res)                  })
//此方法也是一樣 init.get('/banner') .then(res => { console.log(res) }) } })

  攔截器

  請求攔截器和響應攔截器

//請求前          axios.interceptors.request.use(function (config) {              // 可以設置 載入的動畫效果 的展示              //這裡指的是請求之前做點什麼              console.log('正在載入...')              return config          }, function (error) {              // 對請求錯誤做些什麼              return Promise.reject(error);          })            //響應前          axios.interceptors.response.use(function (config) {              // 可以設置 載入的動畫效果 的隱藏              //這裡指的是請求之前做點什麼              console.log('載入完畢')              return config          }, function (error) {              // 對請求錯誤做些什麼              return Promise.reject(error);          })            var app = new Vue({              el: '#box',              data: {                  img: ''              },              mounted(){                  axios.get('http://localhost:3000/api/banner')              }          })