bruh bruh - 1 year ago 206
Javascript Question

Access Vue from external files

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


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

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


// 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(){
'/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
file, I don't have access to "Vue", which I need to define
. 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 Source

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({
  el: '#app',
  render: h => h(App)

Then in the router.js

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


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

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

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

export default router
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download