[Vuejs]-Load Vuex state on startup based on route params

0👍

You can have a reference to the Vuex store in your app.js or main.js file (the entry point where you initialize Vue.) Something like this should work (untested).

import Vue from 'vue'
import Vuex from 'vuex'
import VueRouter from 'vue-router'

Vue.use(Vuex)
Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  routes: [
    // routes here
  ]
})

const store = new Vuex.Store({
  state: {
    tenantId: null,
  },
  mutations: {
    setTenant: (state, tenantId) => (state.tenantId = tenantId)
  }
})

const split = window.location.pathname.split('/')
// find the index of the tenantId
// you can also use RegEx for this
const tenantId = //

store.commit('setTenant', tenantId)

const app = new Vue({
  el: '#app',
  router,
  store
})

0👍

Solution that worked for me, was to add a beforeEach inside App.vue where I also have a reference to Vuex store.

    // App.vue
    created() {
      this.$router.beforeEach(async (to, _, next) => {
        if (to.params && to.params.tenantId) {
          const id = parseInt(to.params.tenantId, 10);
          if (id != this.$store.state.tenantId) {
            const data = await dataService.getById(id);
            this.set_data(data );
          }
        }
        next();
      });
    }

Leave a comment