Search code examples
javascriptvuejs2vuexvue-routervue-cli-3

Vm is not defined - vueJS with vueCLI


I'm using vue-cli for my project. vue-route and vuex also added to project. Routes working nice. while I checking vuex store data in route, I getting vm is not defined error. You can find the code blocks below.

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 }
  ]
})

Problem is starting at this point. Auth js has vm defining because of reach the vuex store.

auth js

function checkAuth() {
  vm.$store.getters.getServerPath();
.... bla bla 
.... bla bla 
}

I hope some one give me an advice. If need I can share more details.


Solution

  • 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 than 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 
    }