我正在为项目使用vue-cli。 vue-route和vuex也已添加到项目中。路线运作良好。在检查路由中的vuex存储数据时,出现vm is not defined
错误。您可以在下面找到代码块。
main.js
// Application
var vm = new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
window.vm = vm;
router.js
import Vue from 'vue'
import Router from 'vue-router'
import auth from './controller/authController'
import Login from './views/Login.vue'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{ path: '/', component: Dashboard, beforeEnter: auth.checkAuth },
{ path: '/login', component: Login }
]
})
问题从现在开始。 Auth js由于已到达vuex存储,因此具有vm定义。
身份验证js
function checkAuth() {
vm.$store.getters.getServerPath();
.... bla bla
.... bla bla
}
我希望有人能给我建议。如果需要,我可以分享更多详细信息。
答案 0 :(得分:1)
I think the more standard approach in this cases is to import and export the vuex store itself, not the vue instance.
So in your auth.js
you import the store and then access its getters directly:
import store from '@/app/store/main.store'; // or whatever path it is
function checkAuth() {
store.getters.getServerPath();
.... bla bla
.... bla bla
}
While I believe this is better that exporting the instance (or the store) to window
, you're asking about why vm
is undefined in your code. Of that I'm not sure,
did you try to reference the vm
directly from window
? I don't really know, but vue-cli code or babel's probably set the strict mode
, so you need to explicitly reference window
properties from window
:
function checkAuth() {
window.vm.$store.getters.getServerPath();
.... bla bla
.... bla bla
}
答案 1 :(得分:0)
You could export and import the vue instance rather than relying on the window object being available.
main.js
// Application
var vm = new Vue({
router,
store,
render: h => h(App)
})
vm.$mount('#app')
export const vueInstance = vm
auth.js
import { vueInstance } from '@/main'
function checkAuth() {
vueInstance.$store.getters.getServerPath();
.... bla bla
.... bla bla
}
答案 2 :(得分:0)
看起来像您在安装中使用VueCLI3。
尝试将其放入window.
中。
main.js
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
router.js
import auth from './auth'
...
{ path: '/', component: Dashboard, beforeEnter: auth.checkAuth }
auth.js
import store from './store'
...
function checkAuth() {
store.getters.getServerPath();
}
export default checkAuth