Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register global components with vue-router

Tags:

I'm using Vue.js with the vue-cli. I chose for the webpack setup. I wired up the main.js file for routing, though I can't find a way to globally register my components.

main.js

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App'
import Companies from './components/pages/Companies'
import Income from './components/pages/Income'
import Login from './components/pages/Login'

Vue.use(VueRouter)

let router = new VueRouter()

router.map({
  '/companies': {
    component: Companies
  },
  '/income': {
    component: Income
  },
  'login': {
    component: Login
  }
})

router.start(App, 'body')

App.vue

<template>
  <div>
    <router-view></router-view>
  </div>
</template>
<script>
import {Auth} from './lib/api'
import Loader from './components/Loader'

export default {
  components: {
    Loader
  },
  ready () {
    Auth.isLoggedIn().then(
      (response) => {
        if (response.data === false) {
          this.$router.go('/login')
        } else {
          this.$router.go('/companies')
        }
      },
      (response) => {
        this.$router.go('/login')
      }
    )
  }
}
</script>

When I use my Loader component in some view, I get the following warning.

[Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.

I provided the name in the component and it didn't make any difference. I'm using the loader-component in the login-view.
I found out that I should either define the component in the component that I'm going to use it or globally. Though, I can't find out how to define it globally with the routing.

like image 226
Swimburger Avatar asked Mar 16 '16 04:03

Swimburger


Video Answer


1 Answers

The way you have it set up now, The loader component is only locally available in the template of the App component.

Routing has no influence on global component registration, just do it like without a router:

// main.js, before all the router stuff:
import Loader from './components/Loader'
Vue.component('loader', Loader)

or register it locally in your Login component. As you already did it in App.vue, you know what to do with Loader.vue

like image 98
Linus Borg Avatar answered Oct 10 '22 07:10

Linus Borg