【问题标题】:Nuxt and $auth in Fetch()Fetch() 中的 Nuxt 和 $auth
【发布时间】:2021-09-15 12:07:45
【问题描述】:

我的 $auth 有问题...

在一个页面中,我必须验证 $auth.loggedIn 的值。

<template>
   {{ this.$auth.loggedIn }}
</template>
<script>
   export default{
       async fetch(){
          if(this.$auth.loggedIn){
            console.log('User connected')
          }else{
            console.log('User not connected')
          }
       }
    }
</script>

我的模板中的第一个 $auth.loggedIn 显示为 TRUE(没关系),但我的 console.log 显示“用户未连接”...

这怎么可能? 看来我对 $router / $route 变量有同样的问题......

非常感谢! 文森特

【问题讨论】:

    标签: authentication fetch nuxt.js


    【解决方案1】:

    fetch 在渲染路由时在服务器端调用,在导航时在客户端调用。

    因此,如果它正在渲染您的路由,它会在服务器端初始化,并且由于 this.$auth 仅在 客户端 上可用,因此无法访问它。

    尝试通过app访问它

    async fetch ({ app }) {
          if(app.$auth.loggedIn){
            console.log('User connected')
          }else{
            console.log('User not connected')
          }
    }
    

    关于参数问题,您可以像下面这样访问:

    async fetch ({ params }) {
            console.log(params.id)
    }
    

    async fetch ({ route}) {
            console.log(route.params.id)
    }
    

    【讨论】:

    • 好的,谢谢您的回答。但是,我该怎么办?我需要根据 $auth.loggedIn 的值在 fetch() 中构造我的页面...!
    • 我看到:“对于插件、asyncData、fetch、nuxtServerInit 和中间件,您可以从 context.$auth 访问它”。但如果我使用 contect.$auth,我有一个“未定义”错误:(
    • @VinParker,试试上面的代码访问 $auth 看看它是否有效。
    • $auth 似乎更好,但现在,我的 this.$route.params.id 出现错误(TypeError: Cannot read property 'params' of undefined)。
    • @VinParker,更新了我关于参数的答案,试试吧。如果对您有用,请不要忘记将其标记为最佳答案:)
    猜你喜欢
    • 2021-01-19
    • 2022-01-26
    • 2019-02-21
    • 2021-08-15
    • 2020-06-11
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 2019-08-06
    相关资源
    最近更新 更多