简体   繁体   中英

this.$route undefined in VueJS (without using arrows)

For some reason, this.$route is undefined for me. I have just started building my Vue application:

window.Vue = require('vue');

new Vue({
    el : '#break-container',
    data : {
        break : null
    },
    methods : {
        fetchBreak : function(){
            console.log(this.$route);    //undefined
        },
    },
    mounted : function(){
        this.fetchBreak();
    },
});

I see a bunch of questions on SO about this, but every time the problem seems to be that they are using arrow notation.

In my case, when I do console.log(this) there is no $route key in the printed object at all. The keys ( $attrs, $children, ... , $vnode, break ).

What can I do to resolve this?

As I understand it, this.$route is only available on Vue instances if you register your router when you create your Vue app. Your code appears to be missing the router definition and subsequent initialisation on the Vue instance

new Vue({
    el : '#break-container',
    // Register your router
    router: router,
    data : {    
        break : null   
    },
    methods : {
        fetchBreak : function(){
            console.log(this.$route);    //undefined
        },
    },
    mounted : function(){
        this.fetchBreak();
    },
}); 

See the sample code here for a full-fledged example. From the page above:

By injecting the router, we get access to it as this.$router as well as the current route as this.$route inside of any component

EDIT:

Pasting some example code from the link above for clarity. Note the steps 0-4 in the comments. Odds are, one of those steps are missing in your code:)

// 0. If using a module system (e.g. via vue-cli), import Vue and VueRouter
// and then call `Vue.use(VueRouter)`.

// 1. Define route components.
// These can be imported from other files
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }

// 2. Define some routes
// Each route should map to a component. The "component" can
// either be an actual component constructor created via
// `Vue.extend()`, or just a component options object.
// We'll talk about nested routes later.
const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

// 3. Create the router instance and pass the `routes` option
// You can pass in additional options here, but let's
// keep it simple for now.
const router = new VueRouter({
  routes // short for `routes: routes`
})

// 4. Create and mount the root instance.
// Make sure to inject the router with the router option to make the
// whole app router-aware.
const app = new Vue({
  router
}).$mount('#app')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM