首先理解需求
当我们需要从项目 index 页面,跳转到 logs 页面时:
- 若不存在 logs 页面,则跳转到新的 logs 页面;
- 若存在 logs 页面,则跳转到这个已打开的 logs 页面;
- 并且当我们从 logs 页面返回 index 页面时,同理。
成果展示(主要展示两页面之间的跳转功能)
实现方案:
- window.name:为当前页面挂载一个name,当该页面在浏览器打开时,标识当前页面;
- window.open(url,name) :(多参数,详见:window.open() 参数)
- url:打开页面的路径;
- name:判断当前所有已经打开的页面中的 name,有没有与 name 值相同的页面,如果有就跳转过去并刷新这个页面,没有就打开一个新页面;
1. 首页 index.html
<div id="app">
<button class="btn" @click="linkTo('./logs.html','logs')"></button>
</div>
<script>
const app = new Vue({
el:"#app",
beforeCreate: function(){
// 设置当前 window.name 为 index,其他页面使用 open() 向 index 跳转时,直接返回已创建 index 的窗体;
window.name = 'index'
},
methods: {
// url:跳转的路径
// name:跳转目标的 name
linkTo(url,name){
window.open(url,name)
}
}
})
</script>
2. 日志 logs.html
<div id="logs">
<button class="btn" @click="linkTo('./index.html','index')"></button>
</div>
<script>
const app = new Vue({
el:"#logs",
beforeCreate: function(){
// 设置当前 window.name 为 logs,其他页面使用 open() 向 logs 跳转时,直接返回已创建 logs 的窗体;
window.name = 'logs'
},
methods: {
// url:跳转的路径
// name:跳转目标的 name
linkTo(url,name){
window.open(url,name)
}
}
})
</script>