Registering vue components globally
Even simpler you may import global components like so:
In your main.js
. (Note Vue.component()
must be called before new Vue()
)
Vue.component(
'MyComponent', () => import('./components/MyComponent')
)
A combination of multiple solutions which i believe is the cleanest approach:
global-components.js:
import Vue from 'vue'
const components = {
'comp1': () => import('components/comp1'),
'comp2': () => import('components/comp2'),
}
Object.entries(components).forEach(([name, component]) => Vue.component(name, component))
main.js:
import 'global-components'
As another option in addition to @Odyssee's answer, if you want to avoid globals, is to create a file, say globalComponents.js
with the following contents:
import List from '@/components/List.vue'
import ListHeader from '@/components/ListHeader.vue'
import ListItem from '@/components/ListItem.vue'
export default {
'oi-list': List,
'oi-list-header': ListHeader,
'oi-list-item': ListItem
}
And you can use it as follows:
<script>
import GlobalComponents from '@/globalComponents.js'
export default {
name: "Tasks",
components: {
...GlobalComponents
}
<script>
This is easy to accomplish. You can register components globally in the main.js file.
import MyComponent from '@/components/MyComponent'
Vue.component('my-component-name', MyComponent)
Now you can use <my-component-name />
everywhere.
A cleaner way, without bloating your main.js
, is to import your component in an index.js file in your components folder like this.
import Vue from 'vue'
import MyComponent from '@/components/MyComponent'
Vue.component('my-component-name', MyComponent)
Later you can add this line to your main.js
to load the registered components.
import '@/components'
the docs: https://v2.vuejs.org/v2/guide/components-registration.html