bruh bruh - 2 months ago 40
Javascript Question

Access Vue from external files

I would like to define my routes in an external file for readability.

My

main.js
file is where I initiate my Vue app. Seen below:

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App'

vue.use(VueRouter)

// I would like these route definitions to be contained in their own file
var Monday = Vue.extend({ template: '<div>Monday view<div>' })
var Tuesday = Vue.extend({ template: '<div>Tuesday view<div>' })
...

var router = new VueRouter()

router.map({
'/monday': { component: Monday },
'/tuesday': { component: Tuesday }

router.start(App, 'body)


I would prefer to separate the route definitions
var Monday = Vue.extend({ ... })
etc, into their own files for readability when the application scales.

The problem: if I was to create a
RouteDefinitions.js
file, I don't have access to "Vue", which I need to define
Vue.extend
. Should I
import Vue from 'vue'
again from inside RouteDefinitions.js? Is this a red flag? Or should I simply keep all my route logic inside main.js?

Answer

You can do it. In your main.js do something like this

import Vue from 'vue'
import router from './config/router'

Vue.router = router

new Vue({
  router,
  el: '#app',
  render: h => h(App)
})

Then in the router.js

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

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [ 
    /* your routes definition here */ 
  ]
})

router.beforeEach((route, redirect, next) => {
  /* your route hooks */
  next()
})

router.afterEach(function (transition) {
  /* your route hooks */
})

export default router
Comments