vue的jsonp写法
1、在package中引入jsonp
"jsonp": "^0.2.1"
命令:cnpm i jsonp -S
2、在src下新建api目录并建立config.js文件
export const commonParams = {
g_tk: 5381,
format: "jsonp",
inCharset: "utf-8",
outCharset: "utf-8",
notice: 0,
}
export const options = {
param: 'jsonpCallback'
}
3、在src下建立common/js/jsonp.js文件
import originJSONP from 'jsonp'
export default function jsonp(url, data, option) {
url += (url.indexOf('?') < 0 ? '?' : '&') + param(data)
return new Promise((resolve, reject) => {
originJSONP(url, option, (err, data) => {
if (!err) {
resolve(data)
} else {
reject(err)
}
})
})
}
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) : ''
}
4、引用 src/api/文件.js
import jsonp from 'common/js/jsonp'
import {commonParams, options} from './config'
export function getSingerList() {
const url = 'https://c.y.qq.com/v8/fcg-bin/v8.fcg'
const data = Object.assign({}, commonParams, {
platform: 'yqq',
needNewCode: 0,
channel: 'singer',
page: 'list',
key: 'all_all_all',
pagesize: 100,
pagenum: 1,
loginUin: 0,
hostUin: 0
})
return jsonp(url, data, options)
}
5、使用
import {getWeather} from 'api/weather'
_getWeather: function () {
getWeather(this.district).then(response => {
if (response.desc == "OK") {
this.weatherinfo = response.data
}
}, response => {
// error callback
})
}

浙公网安备 33010602011771号