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');
};
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.