Vue.js loading single-file components

Dmitry picture Dmitry · Jun 15, 2017 · Viewed 20.1k times · Source

I'm new to Vue.js and want to use single-file components, but I don't understand the workflow.

For example, I have three components: App, Grid and List

App.vue

<template>
    <div id="app">
        <div id="grid"></div>
        <div id="right"></div>
    </div>
</template>

<script>
    export default {
        name: 'app',
        data () {
            return {
                message: 'Hello Vue!'
            }
        }
    }
</script>

Grid.vue

<template>
    <div id="left"></div>
</template>

<script>
    export default {
        name: 'grid',
        data: function () {
            return {
                grid: 'some-data'
            }
        }
    }
</script>

List.vue

<template>
    <div id="right"></div>
</template>

<script>
    export default {
    name: 'list',
    data: function () {
        return {
            text: 'some-text'
        }
    }
}
</script>

Main.js

import Vue from 'vue'
import App from './vue/App.vue'
import Grid from './vue/Grid.vue'
import PatternList from './vue/PatternList.vue'

new Vue({
    el: '#app',
    render: h => h(App)
});

new Vue({
    el: '#grid',
    render: h => h(Grid)
});

new Vue({
    el: '#right',
    render: h => h(PatternList)
});

It works but I hope this isn't the right way to create nested components.

Can anyone show the way it should be done? Thanks

Answer

thanksd picture thanksd · Jun 15, 2017

You can register components using the Vue.component method:

import Vue from 'vue'
import App from './vue/App.vue'
import Grid from './vue/Grid.vue'
import PatternList from './vue/PatternList.vue'

Vue.component('grid', Grid);
Vue.component('pattern-list', PatternList);

new Vue({
  el: '#app',
  render: h => h(App)
});

And then add them to the App template directly using their tag name:

<template>
  <div id="app">
    <grid></grid>
    <pattern-list></pattern-list>
  </div>
</template>

This registers the components globally, meaning that any Vue instance can add those components to their templates without any additional setup.


You can also register components to a Vue instance, like so:

new Vue({
  el: '#app',
  render: h => h(App),
  components: {
    'grid': Grid,
    'pattern-list': PatternList
  }
});

Or within the script tag of a single-file component:

<script>
import Grid from './vue/Grid.vue'

export default {
  name: 'app',
  components: {
    'grid': Grid,
    'pattern-list': PatternList
  }
});
</script>

This registers the components just to that Vue instance, meaning that those registered components will only be available to use within the template for that Vue instance. A child component would not have access to those registered components unless those components are also registered to the child Vue instance.