Skip to content Skip to sidebar Skip to footer

Can't Access Root Data In Vuejs

It's my first post on stackoverflow, so sorry in advance if I do something incorrectly. My question; I've setup a VueJS project, and I'm trying to reach data that I put in the App.

Solution 1:

Vuex is fine and all, but if you just want to expose a property to all of your views in a router based app, you can set it on the router-view.

<router-view :count="count"></router-view>

Then your view component just needs to accept it as a prop.

exportdefault {
    props:["count"],
    name: 'RacePilot',
    mounted() {
        console.log(this.count);
    }
}

Solution 2:

this.$root references the top level Vue instance (new Vue...) and not the App VueComponent.

it is really hacky, other solutions are preferable, but this could work:

newVue({
    el: '#app',
    router,
    template: '<App/>',
    components: { App },
    methods: {
      getCount() {
        returnthis.$children[0].count
      }
    },
});

and using getCount() in RacePilot.vue:

exportdefault {
    name: 'RacePilot',
    mounted() {
        console.log(this.$root.getCount());
    }
}

Solution 3:

It should had worked as it is, as it is working here.

However a better way to manage global variables, which are available across components should be solved by state machine. Vue has Vuex for that purpose as stated here.

Solution 4:

You should not do it like that.

Definitely you should not try to access other components like that.

To share data between components you can either use props (one-way binding) or Vuex to make data accessible and editable from all components through store.

You can use global $store or $router if you will start your Vue app this way:

new Vue({
    el: '#q-app',
    router,
    store
    render: h => h(require('./App'))
  })

Then you can access store (for state change or access state (do not mutate state this way)) - this.$store.state.yourStaneName

Solution 5:

You are trying to access data which is stored in App.vue but this data will be local to the component and not accessible globally.

App.vue is not the root instance (referred to by $root), instead it is the first component within the root instance which is actually created at main.js. It is during this creation time, you need to pass the data which will then be exposed for all child components via $root.

Here is the relevant portion of main.js, modified accordingly :-

new Vue({
    el: '#app',
    data: { count: 0 },
    router,
    template: '<App/>',
    components: { App }
});

Tip : To confirm that App.vue is indeed the first child of root instance, try comparing the references of this.$root with this.$parent. It should returntrue which means that root instance is the parent of App.vue.

References :-

https://vuejs.org/v2/guide/instance.htmlhttps://vuejs.org/v2/api/#vm-roothttps://vuejs.org/v2/guide/components-edge-cases.html#Accessing-the-Root-Instance

Post a Comment for "Can't Access Root Data In Vuejs"