总得来说,前端进行页面跳转的的途径还是蛮多的,下面就列举一些比较常用的方式。
第一种:超链接
例子:
<a href="https://www.baidu.com" title="点击进入百度" target="_blank">点击进入百度</a>
其中属性
target有以下的值可供选择,_self是默认值,可不填。因此使用频率较高的值是_blank,其可以在新窗口打开页面。| 值 | 描述 |
|---|---|
| _blank | 在新窗口中打开被链接文档。 |
| _self | 默认。在相同的框架中打开被链接文档。 |
| _parent | 在父框架集中打开被链接文档。 |
| _top | 在整个窗口中打开被链接文档。 |
| framename | 在指定的框架中打开被链接文档。 |
第二种:JS方式
通过js方式跳转页面主要依赖于window的两个属性,
1. window.location
window.location 对象可用于获取当前页面地址(URL)并把浏览器重定向到新页面。
window.location对象可不带 window 前缀书写。
一些例子:
- window.location.href 返回当前页面的 href (URL)
window.location.href='https://www.baidu.com'- window.location.replace 用新的文档替换当前文档,没有返回功能
window.location.replace("https://www.baidu.com")- window.location.assign 加载新文档,和window.location.href没什么区别
window.location.assign("https://www.baidu.com")2. window.open
打开一个新的浏览器窗口或查找一个已命名的窗口。
window.open("https://www.baidu.com",'_blank')其中window.open的第二个属性有以下的值可供选择,
- _blank - URL加载到一个新的窗口。这是默认
- _parent - URL加载到父框架
- _self - URL替换当前页面
- _top - URL替换任何可加载的框架集
- name - 窗口名称
需要特别注意的是,_blank虽然可以打开一个新窗口,但也会受到浏览器限制,可能会被浏览器拦截。
第三种:JS创建A标签
超链接打开新窗口的方式还是挺实用的,只是在有些情境下可能不太方便,比如,对某个非超链接的元素进行操作,就无法使用_target,而如果绑定click事件,执行window.open()方法,又有被浏览器拦截的风险,实在不与推荐,这种情况下,使用下面的方法可以很好得解决问题。
<p @click="toPage">点击进入百度</p>
<script>
methods: {
// 创建超链接,不会被拦截
createSuperLabel(url, id) {
let a = document.createElement("a");
a.setAttribute("href", url);
a.setAttribute("target", "_blank");
a.setAttribute("id", id);
// 防止反复添加
if(!document.getElementById(id)) {
document.body.appendChild(a);
}
a.click();
},
toPage(){
let uri="http://www.baidu.com";
let id="new_a"
this.createSuperLabel(uri,id)
}
}
</script>如果大家有什么比较好的方法也欢迎评论留言。