先看最終效果
1.png
在老項(xiàng)目中添加
在頁面需要展示內(nèi)容的地方放一個(gè) iframe 標(biāo)簽用于導(dǎo)入打包后的代碼,如上圖的右側(cè)匆绣,代碼如下:
<html>
<div id="main">
<!-- menu 部分省略 -->
<!-- content 部分 -->
<iframe :src="contentSrc" id="myiframe" name="myiframe" style="width: 100%;" scrolling="no"frameborder="0"></iframe>
</div>
</html>
<script>
// data 中聲明 contentSrc,切換菜單時(shí)改變 contentSrc,同時(shí)調(diào)用 setIframeHeight 函數(shù)
new Vue({
el: '#main',
data: {
contentSrc: './index.html#/page1' // 路由地址
}
})
</script>
<script>
// 改變 iframe 高度
function setIframeHeight(appHeight) {
var iframe = document.getElementById('myiframe');
if (iframe) {
iframe.height = appHeight || 800;
}
}
</script>
在 vue-cli 項(xiàng)目中添加
要保證頁面高度改變時(shí)什黑, iframe 也能同時(shí)改變崎淳,需要在vue-cli 開發(fā)的項(xiàng)目中使用 element-resize-detector 檢測(cè) div 的高度變化,div 高度改變時(shí)調(diào)用上方聲明的 setIframeHeight 函數(shù)把高度作為參數(shù)傳入愕把。在 app.vue 添加代碼如下:
// 安裝
npm i element-resize-detector
<script>
// 引入
import elementResizeDetectorMaker from "element-resize-detector";
export default {
name: "app",
mounted() {
// 綁定hashchange事件處理函數(shù)
window.addEventListener("hashchange", () => {
var currentPath = window.location.hash.slice(1); // 獲取輸入的路由
if (this.$router.path !== currentPath) {
this.$router.push(currentPath); // 動(dòng)態(tài)跳轉(zhuǎn)
}
}, false);
// 監(jiān)聽 div 高度
const _this = this;
const erd = elementResizeDetectorMaker();
erd.listenTo(document.getElementById("app"), element => {
_this.$nextTick(() => {
if (typeof window.parent.setIframeHeight === "function") {
// 調(diào)用改變高度方法
window.parent.setIframeHeight(element.offsetHeight);
}
});
});
}
};
</script>
這樣 iframe 的高度就隨著 div 的高度變化而變化拣凹,就完成了老項(xiàng)目中嵌套 vue 單頁應(yīng)用(SPA)