Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access this.$root in Vue.js 3 setup()

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
like image 559
Daniel_Knights Avatar asked Sep 24 '20 05:09

Daniel_Knights


People also ask

How do you access props on setup Vue?

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.

What is Vue setup ()?

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.

How do you access a root component from a child instance in Vue?

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.


1 Answers

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) 
}
like image 139
Boussadjra Brahim Avatar answered Sep 22 '22 06:09

Boussadjra Brahim