在将前端打包并和后端连起来以后,我发现百度地图api的接口又不能用了,但之前明明是好的。查了一下发现,这还是跨域问题。之前解决的方法是设置了代理,但一旦进行了打包,代理就不再起作用了,因此要采用其他的方式解决。幸好百度地图api提供了这种方式,也就是在之前的接口链接最后加一个"&callback=方法"
,其中方法是你接收到的返回数据进行处理的方法名,然后需要用的到jsonp插件,安装和引入方法和之前一样。使用方法如下:
var url =
"http://api.map.baidu.com/place/v2/search?query=" +
encodeURIComponent(this.searchScenic) +"&tag="+
encodeURIComponent("旅游景点")+ "®ion=" +
encodeURIComponent(this.city) +
"&output=json&page_size=4&page_num=" +
this.count +
"&ak=000"+"&callback=loadScenic";
this.$jsonp(url)
.then((res) => {
this.loadScenic(res);
})
.catch((res) => {
alert("加载出错了!");
});
loadScenic(res){
this.loading=false;
var array = res.results;
if (array == undefined || array.length <= 0) {
console.log("no");
this.noMore = true;
} else {
array.forEach((item, index, array) => {
this.scenics.push({
name: item.name,
address: item.address,
});
});
this.count = this.count + 1;
}
},
要注意在这里的返回值处理方法传入的res中是只有data这部分的,因此处理数据时不需要再用res.data提取其中的数据了,只需要res就可以了。