通过vue提供的keep-alive减少对服务器的请求次数

2020-06-12 21:18:07易采站长站整理

我这里使用的是高德地图,在mounted中初始化map,代码示例如下:


export default {
name: 'transferMap',
data: function () {
return {
map: null,
}
},
methods: {
initData: function () {},
searchTransfer: function (type) {},
// 地图渲染 这个在transfer-map.html中使用
renderTransferMap: function (transferMap) {}
},
mounted: function () {
this.map = new AMap.Map("container", {
showBuildingBlock: true,
animateEnable: true,
resizeEnable: true,
zoom: 12 //地图显示的缩放级别
});
},
activated: function () {
let _this = this;
_this.initData();
// 设置title
setDocumentTitle('换乘地图');
_this.searchTransfer(_this.policyType).then(function (result) {
// 数据加载完成
// 换乘地图页面
let transferMap = result.plans[_this.activeIndex];
transferMap.origin = result.origin;
transferMap.destination = result.destination;
// 填数据
_this.transferMap = transferMap;
// 地图渲染
_this.renderTransferMap(transferMap);
});
},
deactivated: function () {
// 清理地图之前的标记
this.map.clearMap();
},
}

6. document.title修改

这个不是 keep-alive 的问题,不过我也在这里分享下。

问题是,使用下面这段方法,可以修改Title,但是页面来回切换多次后就不生效了,我也不知道为啥,放到setTimeout中就直接不执行。

document.title = ‘页面名称’;下面是使用2种环境的修复方法:

纯js实现


function setDocumentTitle(title) {
"use strict";
//以下代码可以解决以上问题,不依赖jq
setTimeout(function () {
//利用iframe的onload事件刷新页面
document.title = title;
var iframe = document.createElement('iframe');
iframe.src = '/favicon.ico'; // 必须
iframe.style.visibility = 'hidden';
iframe.style.width = '1px';
iframe.style.height = '1px';
iframe.onload = function () {
setTimeout(function () {
document.body.removeChild(iframe);
}, 0);
};
document.body.appendChild(iframe);
}, 0);
}

jQuery/Zepto实现


function setDocumentTitle(title) {
//需要jQuery
var $body = $('body');
document.title = title;
// hack在微信等webview中无法修改document.title的情况
var $iframe = $('<iframe src="/favicon.ico"></iframe>');
$iframe.on('load', function () {
setTimeout(function () {
$iframe.off('load').remove();
}, 0);
}).appendTo($body);
}

总结