In Vue 2, you can access this.$root inside the created hook. In Vue 3, everything that would have gone inside the created hook now goes in setup().
In setup() we don't have access to this, so, how can we access anything on the root instance?
Say, I set a property on the root instance:
const app = createApp(App).mount('#app');
app.$appName = 'Vue3';
I can access this from mounted() with this.$root.$appName, how can I do this in setup()?
UPDATE
I can access it if I import it:
import app from '@/main';
...
setup() {
    console.log(app.$appName) // Vue3
But, this is a hassle if I have to do this for every file.
UPDATE 2
Another workaround is to use provide() inside App.vue and then inject() in any other components:
setup() {
    provide('$appName', 'Vue3')
setup() {
    inject('$appName') // Vue3
                Accessing Props #The first argument in the setup function is the props argument. Just as you would expect in a standard component, props inside of a setup function are reactive and will be updated when new props are passed in.
Vue 3 introduced the setUp function. It enables us to extract repeatable parts of components into reusable pieces of code. These reusable codes are stored in the form of a function. This function can be used by any component. Its function scope helps us store and protect data.
We can access the root instance of from a child component with the $root property. The code above created a rootFoo computed property from the root Vue instance's foo component and displayed it inside the foo component. So we get foo displayed.
You could define global property in vue 3 :
app.config.globalProperties.appName= 'vue3'
With setup (composition api) you could use getcurrentinstance to get access to that property:
import { getCurrentInstance } from 'vue'
...
setup() {
    const app= getCurrentInstance()
    console.log(app.appContext.config.globalProperties.appName) 
Since you're still able to use the options api you could simply do :
mounted(){
   console.log(this.appName) 
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With