【问题标题】:Can't Parse VueJS 2 hash as an empty string无法将 VueJS 2 哈希解析为空字符串
【发布时间】:2017-06-13 13:02:02
【问题描述】:

我目前正在尝试确定 url 中是否存在哈希,我得到了一些奇怪的结果。下面的代码在使用http://localhost:8080/subscribers#test 之类的 url 运行时可以正确运行并输出为#test,这是完美的,但是当我简单地请求http://localhost:8080/subscribers 时,它会显示为hash: ""。我最初的想法很简单 this.$route.query.hash === '' 根据 chrome 开发工具是正确的。但这里有点奇怪,因为与 nullundefined'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 语句永远不会被验证为真。

【问题讨论】:

  • "" === nullfalse。那是你的问题吗?或者你能澄清一下吗?
  • 您的空/未定义检查在哪里?你的问题不清楚。 Boolean('') === false
  • 让我用更多信息更新它。
  • 添加了更多信息。
  • @thanksd 不,我的问题是为什么空值不能被断言为空字符串或其他任何东西,尽管它在开发工具中显示为空字符串。

标签: javascript hash ecmascript-6 vuejs2 vue-router


【解决方案1】:

您是否尝试过从语句中删除 .query

另请注意,如果您不完全强制刷新,而不仅仅是添加 #test 然后接受 url,您将导致 dom 刷新,但您不会导致路由器更新,这就是您得到奇怪结果的原因从控制台。如果您执行了完全刷新,例如从其他网站返回或来自其他网站,那么它将正确解析 #。

【讨论】:

    【解决方案2】:

    问题出在你的 if 语句中,让你的 if 像这样:

    if (this.$route.hash) {
            console.log('grabbing auth')
          } else {
            console.log('attempting redirect')
            }
    

    【讨论】:

    • 这个声明总是验证为假,这就是我在 SO 上发帖的原因。
    • 刚刚通过发送一个返回为尝试重定向的空字符串来验证这一点,然后尝试向它发送一个返回为尝试重定向的哈希。
    猜你喜欢
    • 2014-07-10
    • 1970-01-01
    • 2019-04-04
    • 2013-02-04
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 2012-10-12
    相关资源
    最近更新 更多