vue使用jsonp抓取qq音樂數(shù)據(jù)的方法
1、安裝jsonp
npm install jsonp
2、創(chuàng)建jsonp.js文件,內(nèi)容如下:
import originJSONP from 'jsonp'
/** * 封裝jsonp
* @param {*} url 原始的jsonp第一個參數(shù)是url,第二個參數(shù)是option,這里為了比較好寫參數(shù)做了下封裝
* @param {obj} data 參數(shù)
* @param {*} option jsonp的option
*/
export default function jsonp (url, data, option) {
// 如果url沒有?就加一個?拼接
url += (url.indexOf('?') < 0 ? '?' : '&') + param(data)
return new Promise((resolve, reject) => {
// 原始jsonp的三個參數(shù),url、option、回調(diào)函數(shù)
originJSONP(url, option, (err, data) => {
// 類似node的設(shè)計,如果err是null,表示成功,data是后端返回的數(shù)據(jù)
if (!err) {
resolve(data)
} else {
reject(err)
}
})
})
}
export function param (data) {
let url = ''
for (var k in data) {
let value = data[k] !== undefined ? data[k] : ''
url += '&' + k + '=' + encodeURIComponent(value)
}
return url ? url.substring(1) : ''
}
3、創(chuàng)建confiig.js文件,內(nèi)容如下:
// 用于存放公共數(shù)據(jù)
export const commonParams = {
g_tk: 5381,
format: 'json',
inCharset: 'utf - 8',
outCharset: 'utf - 8',
notice: 0
}
export const options = {
param: 'jsonpCallback'
}
export const ERR_OK = 0
3、創(chuàng)建recommend.js文件,內(nèi)容如下:
import jsonp from './jsonp'
import { commonParams, options } from './config'
export function getRecommend () {
const url = 'https://c.y.qq.com/musichall/fcgi-bin/fcg_yqqhomepagerecommend.fcg'
const data = Object.assign({}, commonParams, {
platform: 'h5', uin: 0, needNewCode: 1
})
// 這里返回一個promise對象
return jsonp(url, data, options)
}
4、在組件中使用,如musicHall.vue中
<script>
import {getRecommend} from '../api/recommend.js'
import {ERR_OK} from '../api/config.js'
export default {
mounted () {
//在created中也可
this._getRecommend()
},
methods: {
_getRecommend () {
getRecommend().then((res) => {
if (res.code === ERR_OK) {
console.log(res.data.slider)
}
})
}
}
}
</script>
5、總結(jié)
- Object.assign方法用于對象的合并,將源對象(source)的所有可枚舉屬性,復(fù)制到目標(biāo)對象(target)
- Object.assign(target, source1, source2)
- encodeURIComponent(URIstring)函數(shù)可把字符串作為 URI 組件進(jìn)行編碼。 URIstring 必需。一個字符串,含有 URI 組件或其他要編碼的文本。
- substring()方法用于提取字符串中介于兩個指定下標(biāo)之間的字符。
- stringObject.substring(start,stop)包括 start 處的字符,但不包括 stop 處的字符。不接受負(fù)的參數(shù)。
總結(jié)
以上所述是小編給大家介紹的vue使用jsonp抓取qq音樂數(shù)據(jù)的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
從0到1構(gòu)建vueSSR項目之node以及vue-cli3的配置
這篇文章主要介紹了從0到1構(gòu)建vueSSR項目之node以及vue-cli3的配置,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-03-03
elementUI?checkBox報錯Cannot read property &ap
這篇文章主要為大家介紹了elementUI?checkBox報錯Cannot read property 'length' of undefined的解決分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
Vue使用$attrs實現(xiàn)爺爺直接向?qū)O組件傳遞數(shù)據(jù)
這篇文章主要為大家詳細(xì)介紹了Vue如何使用$attrs實現(xiàn)爺爺直接向?qū)O組件傳遞數(shù)據(jù),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2024-02-02
vue3自定義指令自動獲取節(jié)點的width和height代碼示例
這篇文章主要介紹了如何使用ResizeObserver監(jiān)聽組件的寬度和高度,并將其封裝成一個指令以便全局或局部使用,ResizeObserver可以監(jiān)聽元素的多個尺寸屬性,如top、bottom、left等,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-11-11

