'How would you write this using the composition api?

  computed: {
    userName() {
      // (4) Display authenticated user name
      const user = this.$gapi.getUserData()

      return user.accessToken
    },
  },

This is the code im trying to convert to the Vue3 composition API. Essentially i understand i need to import computed and so on but the part i can't seem to work out is how to write this.$gapi.getUserData() in the setup function.

gapi is an imported package im using..



Solution 1:[1]

Global properties are setup on app.config.globalProperties in Vue 3, and the application instance can be retrieved via getCurrentInstance().appContext.

The equivalent Composition API would be similar to this:

import { getCurrentInstance, computed } from 'vue'

export default {
  setup() {
    const currentInstance = getCurrentInstance()
    return {
      userName: computed(() => {
        const user = currentInstance.appContext.config.globalProperties.$gapi.getUserData()
        return user.accessToken
      })
    }
  }
}

demo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1