5

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.vue from another component. To do this, I use this.$root.count for example, but it returns undefined.

Main.js:

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App'

Vue.use(VueRouter);

const router = new VueRouter({
mode: 'history',
routes: [{
    path: '/',
    name: 'home',
    component: function (resolve) {
        require(['./components/Hello.vue'], resolve)
    }
}, {
    path: '/race-pilot',
    name: 'racePilot',
    component: function (resolve) {
        require(['./components/RacePilot.vue'], resolve)
    }
}
});

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

App.vue:

<template>
<div>
    <div class="menu" ref="menu">
        <router-link :to="{ name: 'home' }">Home</router-link>
        <router-link :to="{ name: 'racePilot' }">Race Pilot</router-link>
    </div>
    <div id="app">
        <router-view></router-view>
    </div>
</div>
</template>

<style src="./assets/css/app.scss" lang="scss"></style>

<script>
import Hello from './components/Hello'

export default {
    name: 'app',
    components: {
        Hello
    },
    data () {
        return {
            count: '0'
        }
    }
}
</script>

RacePilot.vue:

<template>
<div class="race-pilot">
</div>
</template>

<script>
export default {
    name: 'RacePilot',
    mounted() {
        console.log(this.$root.count);
    }
}
</script>

So the last log returns undefined. However, if I log this.$root, I do get the object. Anybody any idea? Thanks in advance!

Insurgo
  • 53
  • 1
  • 1
  • 4

6 Answers6

3

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.

export default {
    props:["count"],
    name: 'RacePilot',
    mounted() {
        console.log(this.count);
    }
}
Bert
  • 80,741
  • 17
  • 199
  • 164
  • Only question I would have; what if I'm in a really deep component, three childs away, and want to change the global variable count? Since this.$root doesn't seem to work... – Insurgo Mar 23 '17 at 16:42
  • 1
    Several options. Use Vuex would be what a lot of people would tell you, but I find Vuex to be overkill for small projects. Event bus would be the easiest. Or you could invent your own Vuex-like store that is available to all components using a global mixin. – Bert Mar 23 '17 at 16:49
  • Here's an example of a super simple store for global data http://codepen.io/Kradek/pen/XMqvPo?editors=1010 – Bert Mar 23 '17 at 17:06
  • @BertEvans Nice and clean answer, what's the best way to provide async data (from a server), like user data? – sandrooco May 24 '17 at 08:34
  • @Sandrooco your properties can be async data. When they change, children will receive the updated properties. – Bert May 25 '17 at 15:15
3

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:

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

and using getCount() in RacePilot.vue:

export default {
    name: 'RacePilot',
    mounted() {
        console.log(this.$root.getCount());
    }
}
walpod
  • 61
  • 3
1

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://v2.vuejs.org/v2/guide/instance.html
https://v2.vuejs.org/v2/api/#vm-root
https://v2.vuejs.org/v2/guide/components-edge-cases.html#Accessing-the-Root-Instance

tony19
  • 125,647
  • 18
  • 229
  • 307
ParaBolt
  • 1,593
  • 2
  • 10
  • 16
0

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

Marek Urbanowicz
  • 12,659
  • 16
  • 62
  • 87
0

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.

Community
  • 1
  • 1
Saurabh
  • 71,488
  • 40
  • 181
  • 244
0

You can also make the App component the actual root by passing the component directly to the Vue instance, which would look something like this:

new Vue(App).$mount('#app')

You'll probably have to move the router to App.vue, but this will make sure that this.$root will resolve to your App component directly.