Search code examples
nuxt.jsvue-composition-apinuxt3.jsnuxt-authnuxt-bridge

Nuxt 2 Bridge Composition API: how to access context (such as `$auth`)?


With Nuxt 2 I could do

<script lang="ts">
import Vue from 'vue'

export default class Login extends Vue {
  mounted() {
    if (!this.$auth.loggedIn) {
      this.$auth.login()
    }
  }
}
</script>

How do I change this to Nuxt 2 Bridge Composition API?

<script setup lang="ts">
onMounted(() => {
  // ?
})
</script>

Solution

  • useNuxtApp() gives access to the context:

    <script setup lang="ts">
    onMounted(() => {
      const { $auth } = useNuxtApp()
    })
    </script>
    

    However, at the moment typing with Nuxt 2 Bridge only works on the nuxt2Context property:

    <script setup lang="ts">
    onMounted(() => {
      const { nuxt2Context } = useNuxtApp()
    
      if (!nuxt2Context.$auth.loggedIn) {
        nuxt2Context.$auth.login()
      }
    })
    </script>