Within my app, there is a root page featuring a Navbar component
. I am attempting to access a variable called currentRoute
from this Navbar component. The code in my index.js
file where I have defined currentRoute
is as follows:
import Vue from 'vue';
import routes from './routes';
var app = new Vue({
el: '#app',
data: {
currentRoute: window.location.pathname,
},
computed: {
ViewComponent () {
return routes[this.currentRoute] || routes.NotFound;
}
},
render (h) {
return h(this.ViewComponent)
}
});
window.addEventListener('popstate', () => {
app.currentRoute = window.location.pathname;
});
In addition, I have a home.vue
file which serves as the default route and includes a component named Navbar
. In this component, I am trying to access currentRoute
. Here is what the code looks like:
<template lang="jade">
.navbar
.row
.col.text-center
a.post-outline.navbar--icon(href='/new-post', @click="newPost")
.col.text-center
i.email-outline.navbar--icon
.col.text-center
i.person-outline.navbar--icon
</template>
<script>
import routes from '../../routes';
export default {
props: {
href: String,
required: true
},
computed: {
isActive () {
return this.href === this.$root.currentRoute
}
},
methods: {
newPost: event => {
event.preventDefault();
this.$root.currentRoute = this.href;
window.history.pushState(
null,
routes[this.href],
this.href
)
},
},
}
</script>
The contents of my routes.js file are as follows:
import NotFound from './pages/404.vue';
import Home from './pages/home.vue';
const NewPost = { template: '<p>new post page</p>' }
export default {
'/': Home,
'/new-post': NewPost
}
Despite everything appearing to be in order, I find that this.$root
remains undefined. Where could I be making an error?