window.location
window.location 对象用于获得当前页面的地址 (URL),并把浏览器重定向到新的页面。
location对象的属性
window.location.href
- 获取当前页面的URL
- 设置当前页面的URL
// 1.获取当前页面的URL
// 当前页面的URL为http://demo.com/index
console.log(window.location.href) // 打印结果:http://demo.com/index
// 2.设置当前页面的URL
// 当前页面的URL为http://demo.com/index
mounted() {
// 直接覆盖
window.location.href = `https://baidu.com/`
// URL修改为https://baidu.com/
// 相对路径修改
window.location.href = '/login'
// URL修改为http://demo.com/login
}
window.location.search
- URL中?以及?后面的所有内容
// 当前页面的URL为http://demo.com/index?code=123&page=1&size=10
console.log('search',window.location.search)
// 打印结果:?code=123&page=1&size=10
window.location.host
- 获取主机名,如果端口不是协议默认的80和443,则还会包括冒号:和端口号
// 当前页面的URL为http://e.demo.com
console.log(window.location.host) // e.demo.com:8081
window.location.pathname
- 获取路径部分,从/开始
// 当前页面的URL为http://demo.com/user/index/
console.log(window.location.pathname) // /user/index/
window.location.port
- 获取端口号
// 当前页面的URL为http://demo.com/user/index/
console.log(window.location.port) // 8081
window.location.hash
- 从#开始的URL
// 当前页面的URL为http://demo.com/user/index/#like
console.log(window.location.hash) // like
window.location.hostname
- 主机名,不包括端口号
// 当前页面的URL为http://e.demo.com
console.log(window.location.hostname) // e.demo.com
window.location.protocol
- URL的协议
// 当前页面的URL为http://demo.com
console.log(window.location.protocol) // http:
window.location.origin
- URL的协议,主机名,端口
// 当前页面的URL为http://e.demo.com
console.log(window.location.origin) // http://e.demo.com
location对象的方法
assign()
- 载入一个新的文档,参数为URL字符串
// 跳转到新的页面,点击后退可以返回上一个页面
window.location.assign(url)
reload()
- 重新加载当前网址,相当于浏览器的刷新按钮。参数为布尔值。
- true:服务器请求重新加载当前网页,网页滚动到头部。
- false(空):从本地缓存重新加载当前网页,视口位置回到加载前的位置
window.location.reload(true);
replace()
- 用新的URL替换当前URL,不能后退,浏览历史History中会删除旧的地址
- 用途:判断当前为移动设备时,替换为移动版网页
// 跳转到新的页面,后退不回原来的页面
window.location.replace(url);
toString()
- 获取URL字符串,相当于读取window.location.href
// 当前页面的URL为http://demo.com/user/index/?id=123
window.location.toString() // http://demo.com/user/index/?id=123
参考:1.blog.dselegent.icu/front_end/f… 2.www.runoob.com/jsref/obj-l…