【问题标题】:Write a Global Methods to check authentication in NuxtJS编写一个全局方法来检查 NuxtJS 中的身份验证
【发布时间】:2026-02-20 01:10:01
【问题描述】:

我很难编写一个全局方法来检查 NuxtJS 中的身份验证。我可以在组件中编写 v-if 以显示它是否返回 True 的方法。 我把这段代码放在 layout/default.vue 中,但它不起作用。

/layout/defaut.vue

<script>
import '~/assets/icons'
export default {
  head () {
    return !this.mobileLayout ? {} : {
      bodyAttrs: {
        class: 'mobile'
      }
    }
  },
  created () {
    this.LoggedIn()
  },
  methods: {
    LoggedIn: function () {
      return this.$store.state.authUser
    }
  }
}
</script>

组件:

<template>
  <div v-if="LoggedIn">Authenticated</div >
</template>

错误:

Property or method "LoggedIn" is not defined on the instance but referenced during render

希望大家帮帮我!

【问题讨论】:

    标签: vue.js vuejs2 vue-component nuxt.js


    【解决方案1】:

    因为authUser 在 vuex 中是一个状态属性,而不是一个方法。组件中的LoggedIn 只是从状态返回一个值,不需要是方法。

    您应该使用计算而不是方法。也不需要在created方法中调用LoggedIn,一旦计算,就会自动计算。

    <script>
    import '~/assets/icons'
    export default {
      head () {
        return !this.mobileLayout ? {} : {
          bodyAttrs: {
            class: 'mobile'
          }
        }
      },
      computed: {
        LoggedIn: function () {
          return this.$store.state.authUser
        }
      }
    }
    </script>
    

    或者更好的是,使用来自 vuex 的 mapState,这里记录了 https://vuex.vuejs.org/en/state.html

    <script>
    import Vuex from 'vuex'
    import '~/assets/icons'
    export default {
      head () {
        return !this.mobileLayout ? {} : {
          bodyAttrs: {
            class: 'mobile'
          }
        }
      },
      computed: {
        ...mapState({
            LoggedIn: 'authUser'
        })
      }
    }
    </script>
    

    您的模板不需要更改。

    【讨论】: