bruh
bruh

Reputation: 2295

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?

Upvotes: 2

Views: 2608

Answers (1)

Primoz Rome
Primoz Rome

Reputation: 11021

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

Upvotes: 4

Related Questions