vuejs / composition-api

Composition API plugin for Vue 2

Home Page:https://composition-api.vuejs.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to either use inject or access $root?

Sjoerd82 opened this issue · comments

I'm having some trouble getting acces to global state in the setup function.
Originally I used to use $root, but I've also tried via provide/inject, but in both cases I haven't been able to access the values.

In main.ts, where the app is created:

import VueCompositionAPI from '@vue/composition-api' 
Vue.use(VueCompositionAPI)

new Vue({
    router,
    vuetify,
    data: {
        clientId: null,
    },
    provide () {
        return { userId: 42 }
    },
    render: h => h(App),
    async created() {
        this.$root.clientId = 43
    },
}).$mount('#app')

Then later in some component that uses this composition-api:

Trying to access $root:

export default {
    setup(initProps, setupContext) {
        const refs = setupContext.refs
        console.log(refs) // empty object {}
    }
}

Trying to access inject/provide; method 1/2

import { ref, inject } from '@vue/composition-api'
export default {
    setup() {
        const userID = inject('userID')
        console.log(userID) // undefined
    }
}

Trying to access inject/provide; method 2/2: (this enables the use of the {{userId}} on the template, but still not in the setup).

import { ref, inject } from '@vue/composition-api'
export default {
    inject: ['userId'],
    setup() {
        console.log(userID) // ReferenceError: userId is not defined
    }
}

I've also tried some variations of these, but so far have not been able to access any value in setup()

Never mind! I typed userID instead of userId. Mea culpa.