vue2.x 实现移动音乐播放器——jsonP相关

编程入门 行业动态 更新时间:2024-10-13 20:19:08

vue2.x 实现移动音乐<a href=https://www.elefans.com/category/jswz/34/1769718.html style=播放器——jsonP相关"/>

vue2.x 实现移动音乐播放器——jsonP相关

利用js文件不会被同源政策限制的原理,解决跨域

首先利用npm 安装 jsop的库

npm install jsonp

 相关API

jsonp(url, opts, fn)

  • url (String) url to fetch 接口地址
  • opts (Object), optional
    • param (String) name of the query string parameter to specify the callback (defaults to callback)
    • timeout (Number) how long after a timeout error is emitted. 0 to disable (defaults to 60000) 超时时间,默认一分钟
    • prefix (String) prefix for the global callback functions that handle jsonp responses (defaults to __jp)
    • name (String) name of the global callback functions that handle jsonp responses (defaults to prefix + incremented counter)
  • fn callback 回调函数

The callback is called with err, data parameters.

If it times out, the err will be an Error object whose message is Timeout.

Returns a function that, when called, will cancel the in-progress jsonp request (fn won't be called).

 相关函数和注释如下:

import originJsonp from 'jsonp'
// 引入原始jsonp方法// 下面是自己定义的方法,方法名为jsonp
// url:接口地址
// data:相关参数query
// option:对应库中的option参数
export default function jsonp(url, data, option) {// 检查url第一个符号是否为?,如果没有?,则变成?,否则变成&url += (url.indexOf('?') < 0 ? '?' : '&') + param(data)// resolve:成功回调// reject:失败回调return new Promise((resolve, reject) => {originJsonp(url, option, (err, data) => {// 如果没有错误,返回data,如果有错误,返回错误if (!err) {resolve(data)} else {reject(err)}})})
}
// 设置param函数,进行url拼接,即:新url=传入的url+data
export function param(data) {let url = ''// 循环data,如果data[k] 不为空,则为data[k],否则则为空。不能传undefined给后端for (var k in data) {let value = data[k] !== undefined ? data[k] : ''url += '&' + k + '=' + encodeURIComponent(value)}// 如果url有内容,把第一个&符号去掉return url ? url.substring(1) : ''
}

可将该js文件放入工具类文件夹中,方便复用

以推荐页面为例,使用该方法

在api下创建 recommend.js文件

import jsonp from 'common/js/jsonp'export function getRecommend() {const url = '.fcg'const data = {platform: 'h5',uin: 0,needNewCode: 1,g_tk: 5381,inCharset: 'utf-8',outCharset: 'utf-8',notice: 0,format: 'jsonp'})const options = {param: 'jsonpCallback'}return jsonp(url, data, options)
}

在业务组件中使用

//先引入
import {getRecommend, getDiscList} from 'api/recommend'
//定义一个方法
// 获取qq滚动轮播图_getRecommend() {getRecommend().then((res) => {if (res.code === 200) {this.recommends = res.data.slider}})}
//created中使用
created() {this._getRecommend()
},

 

更多推荐

vue2.x 实现移动音乐播放器——jsonP相关

本文发布于:2024-02-10 16:57:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1676311.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:播放器   音乐   jsonP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!