亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

vue中利用Promise封裝jsonp并調(diào)取數(shù)據(jù)

 更新時(shí)間:2019年06月18日 09:18:28   作者:王梓瑞  
Promise就是一個(gè)給一步操作提供的容器,在這個(gè)容器里,有兩個(gè)階段無(wú)法改變的階段,這兩個(gè)階段在文中給大家提到。對(duì)vue中利用Promise封裝jsonp并調(diào)取數(shù)據(jù) 的相關(guān)知識(shí)感興趣的朋友,跟隨小編一起看看吧

Promise就是一個(gè)給一步操作提供的容器,在這個(gè)容器里,有兩個(gè)階段無(wú)法改變的階段,第一個(gè)階段就是Pending(進(jìn)行),第二個(gè)階段就是結(jié)果階段,包含F(xiàn)ulfilled(成功)、Rejected(失敗)兩個(gè)結(jié)果。

這兩個(gè)結(jié)果不會(huì)改變。然后結(jié)果結(jié)束后就會(huì)用then來(lái)執(zhí)行相應(yīng)的結(jié)果。

new Promise((resolve,reject)=>{
 相應(yīng)操作
 if(異步操作成功){
  resolve(value)
 }else{
  reject(error)
 }
}).then(value=>{
 // 成功后操作
},error=>{
 // 失敗后操作   
})

用Promise封裝jsonp方法

import originJSONP from 'jsonp'
// 這時(shí)候Url是不帶參數(shù)的,我們讓data變成參數(shù),data在具體定義獲取具體內(nèi)容的時(shí)候再單獨(dú)配置
export default function jsonp(url, data, option) {
 // 看url是否有問(wèn)號(hào)的意思就是只在第一次加參數(shù)的時(shí)候加一個(gè)問(wèn)號(hào),剩下就是加&
 url += (url.indexOf('?') < 0 ? '?' : '&') + param(data)
 return new Promise((resolve, reject) => {
  originJSONP(url, option, (err, data) => {
   if (!err) {
    resolve(data)
   } else {
    reject(err)
   }
  })
 })
}
// 將data數(shù)據(jù)遍歷,前提data是一個(gè)數(shù)組
function param(data) {
 let url = ''
 for (var k in data) {
  let value = data[k] !== undefined ? data[k] : ''
  url += `&${k} = ${encodeURIComponent(value)}`
 }
 //刪除第一個(gè)&符號(hào)
 return url ? url.substring(1) : ''
}

定義一個(gè)重復(fù)比較多的配置文件config.js

export const commonParams = {
 g_tk: 5381,
 inCharset: 'utf-8',
 outCharset: 'utf-8',
 notice: 0,
 format: 'jsonp'
}

// jsonp默認(rèn)的options就是jsonpCallback
export const options = {
 param: 'jsonpCallback'
}
export const ERR_OK = 0

然后再進(jìn)行獲取頁(yè)面方法的封裝

import jsonp from 'common/js/jsonp'
import { commonParams, options } from './config'
export function getRecommend() {
 // 獲取qq音樂(lè)的地址
 const url =
  'https://c.y.qq.com/musichall/fcgi-bin/fcg_yqqhomepagerecommend.fcg'
 // object.assign()方法來(lái)合并commonParams對(duì)象和后面的對(duì)象
 const data = Object.assign({}, commonParams, {
  platform: 'h5',
  uin: 0,
  needNewCode: 1
 })
 // 最后返回的是
 return jsonp(url, data, options)
}

再相應(yīng)組件中進(jìn)行調(diào)用

<script>
import { getRecommend } from 'api/recommend'
import { ERR_OK } from 'api/config'
export default {
 created() {
  this._getRecommend()
 },
 methods: {
  _getRecommend() {
   getRecommend().then(res => {
    if (res.code === ERR_OK) {
     console.log(res.data.slider)
    }
   })
  }
 }
}
</script>

然后就可以在控制臺(tái)獲得數(shù)據(jù)了

總結(jié)

以上所述是小編給大家介紹的vue中利用Promise封裝jsonp并調(diào)取數(shù)據(jù),希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!

相關(guān)文章

最新評(píng)論