无法将 VueJS 2 哈希解析为空字符串
Can't Parse VueJS 2 hash as an empty string
我目前正在尝试确定 url 中是否存在哈希,但我得到了一些奇怪的结果。下面的代码当 运行 带有 url 时 http://localhost:8080/subscribers#test
运行s 正确并输出为 #test
这是完美的,但是当我简单地请求 http://localhost:8080/subscribers
它显示为 hash: ""
。我最初的想法很简单 this.$route.query.hash === ''
根据 chrome 开发工具是正确的。但这就是它变得奇怪的地方,因为 null
和 undefined
或 'undefined'
检查两者都不匹配我的 if 语句。
mounted: function () {
if (this.$route.query.hash === '' || this.$route.query.hash === 'undefined' || this.$route.query.hash === null) {
console.log(this.$route.hash)
console.log(this.$route)
console.log('grabbing auth')
} else {
console.log(this.$route.hash)
console.log(this.$route)
console.log('attempting redirect')
}
}
控制台输出,显示为尝试重定向:
有人能知道这是为什么还是我做错了什么?
编辑:
使用 if (this.$route.query.hash) {
也提供了相同的奇怪结果,其中 if 语句从未被验证为真。
问题出在你的 if 语句中,让你的 if 像这样:
if (this.$route.hash) {
console.log('grabbing auth')
} else {
console.log('attempting redirect')
}
您是否尝试过从声明中删除 .query
?
另请注意,如果您不完全强制刷新,而不是仅添加 #test 然后接受 url,您将导致 dom 刷新,但不会导致路由器更新这就是为什么你从控制台得到奇怪的结果。如果您执行了完全刷新,例如从其他网站返回或来自其他网站,那么它将正确解析 #。
我目前正在尝试确定 url 中是否存在哈希,但我得到了一些奇怪的结果。下面的代码当 运行 带有 url 时 http://localhost:8080/subscribers#test
运行s 正确并输出为 #test
这是完美的,但是当我简单地请求 http://localhost:8080/subscribers
它显示为 hash: ""
。我最初的想法很简单 this.$route.query.hash === ''
根据 chrome 开发工具是正确的。但这就是它变得奇怪的地方,因为 null
和 undefined
或 'undefined'
检查两者都不匹配我的 if 语句。
mounted: function () {
if (this.$route.query.hash === '' || this.$route.query.hash === 'undefined' || this.$route.query.hash === null) {
console.log(this.$route.hash)
console.log(this.$route)
console.log('grabbing auth')
} else {
console.log(this.$route.hash)
console.log(this.$route)
console.log('attempting redirect')
}
}
控制台输出,显示为尝试重定向:
有人能知道这是为什么还是我做错了什么?
编辑:
使用 if (this.$route.query.hash) {
也提供了相同的奇怪结果,其中 if 语句从未被验证为真。
问题出在你的 if 语句中,让你的 if 像这样:
if (this.$route.hash) {
console.log('grabbing auth')
} else {
console.log('attempting redirect')
}
您是否尝试过从声明中删除 .query
?
另请注意,如果您不完全强制刷新,而不是仅添加 #test 然后接受 url,您将导致 dom 刷新,但不会导致路由器更新这就是为什么你从控制台得到奇怪的结果。如果您执行了完全刷新,例如从其他网站返回或来自其他网站,那么它将正确解析 #。