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, eg 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 .
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
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.