播放器——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 tocallback
)timeout
(Number
) how long after a timeout error is emitted.0
to disable (defaults to60000
) 超时时间,默认一分钟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 toprefix
+ incremented counter)fn
callback 回调函数The callback is called with
err, data
parameters.If it times out, the
err
will be anError
object whosemessage
isTimeout
.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相关
发布评论