Global components in Vue (nuxt)

Warre Buysse picture Warre Buysse · Mar 27, 2017 · Viewed 13.3k times · Source

While building a Vue application we re-use certain Vue components in every template. Our grid system exists out of .region, .layout, .grid, .column elements. All of them are separate Vue components (, ...).

We now end up doing this in every template:

import BlMain from '~components/frame/main/Main.vue'
import BlRegion from '~components/frame/region/Region.vue'
import BlLayout from '~components/frame/layout/Layout.vue'
import BlGrid from '~components/frame/grid/Grid.vue'
import BlColumn from '~components/frame/column/Column.vue'

Is there a way to import Vue Components globally in your project? Is it an option to create a component Frame.vue that contains the imports above and add the Frame component in every template? How do other FE frameworks tackle this?

We are using Nuxt JS upon Vue.

Answer

motia picture motia · Jun 12, 2017

You should use a plugin that registers the account.

// plugins/bl-components.js

import Vue from 'vue'
import BlMain from '~components/frame/main/Main.vue'
import BlRegion from '~components/frame/region/Region.vue'
import BlLayout from '~components/frame/layout/Layout.vue'
import BlGrid from '~components/frame/grid/Grid.vue'
import BlColumn from '~components/frame/column/Column.vue'

const components = { BlMain, BlRegion, ... }

Object.entries(components).forEach(([name, component]) => {
  Vue.component(name, component)
})


// nuxt.config.js
export default {
  plugins: ['~plugins/bl-components']
}