Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

When trying to use Vue.js with vue-resource and vue-router a error is shown:

ReferenceError: can't access lexical declaration `vm' before initialization

As far a I tracked the error down it only appears when the page is loaded with an initial route, e.g. test.com/#/files (error) and test.com/ (no error). If all code of requestDirectory() is replaced by next() the error will not be shown. So it seems inherit to code structure. Any ideas?

const routerComponents = {
    home: {     template: '<p>Home ...</p>' },
    files: { template: '<p>Files</p>' }
};

function requestDirectory(to, from, next) {
    console.log("Loading files in ...");
    vm.$http.post('/api/dir', {dir: 'photos'}).then((res) => {
        console.log("done");
        next()
    }, (err) => {});
}

const router = new VueRouter({
    routes: [
        { path: '/', component: routerComponents.home },
        { path: '/files', component: routerComponents.files, beforeEnter: requestDirectory }
    ]
});

const vm = new Vue({
    data: {
        title: 'Home'
    },
    router: router
});

window.onload = function() {
    vm.$mount('#app');
};
share|improve this question
up vote 0 down vote accepted

You can't access vm or this in beforeEnter callback because at this point component's instance has not been created yet. Try to move your code to one of provided by component instance events such as created.

UPDATED

Just replace vm.$http with a global shortcut Vue.http

Found in a documentation there.

share|improve this answer
    
I read this, but this would mean one cannot use vue-router and vue-resource?? – Bernd Jan 12 at 16:52
    
there are different types of components - router components is all about routing, as i understand it right. Anyway, would you try to access it globally via Vue.http instead of vm.$http? – Panama Prophet Jan 12 at 17:10
    
Vue.http works, but it leads to a new error "next undefined".All in all I placed the HTTP request in the components created callback an it works. – Bernd Jan 13 at 12:30

This is the difference between var and const/let in ES6.

ES6 will still hoist the let/const variable to the top of the block. However, using the variable before the const/let declaration will result in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.

For further information see, ECMAScript® 2017 Language Specification 13.3.1 Let and Const Declarations

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.