Dev Notes

Software Development Resources by David Egan.

Vue Components


Front End, JavaScript, Vue
David Egan

Vue Components

Vue provides a way for you to abstract elements into re-usable pieces (or in other words, components!).

Vue components are custom elements that have behaviour attached to them by the Vue compiler. For example, you might define an <article> component that encapsulates all the code relating to display of content associated with an article.

I’m new to Vue so please treat this content with suspicion! If you have any Vue tips, or if you’d like to point out where I’m going wrong, please leave a comment.

Data can be passed into components by means of props and slots.

Vue provides several methods for registering and using components. In general, global components are registered by means of Vue.component(id, definition), where:

  • id is a string that will be set to the component name
  • definition is a function or an options object (that might define markup, props etc)

Registering a Component: Basic Method

Register an “news-article” component - defines a <news-article></news-article> that can be used within HTML:

// Register component before instantiating the Vue instance
// Reference the template inline
Vue.component('news-article', {
  template: `
  <div class="article"><h2>This is an Article Title</h2></div>
  `
});

// New Vue root instance
new Vue({
  el: '#app'
})

In this example, the HTML for the template is passed to the constructor inline. For a project of any size, this is likely to be too messy.

Another option is to define the HTML for the template as a script tag of type “text/x-template” (which will be ignored by browsers):

<script type="text/x-template" id="news-article-template">
  <h2>This is an Article Title</h2>
</script>

<script type="text/javascript">
Vue.component('news-article', {
  template: "#news-article-template"
});
</script>

The constructor now references the id of the “text/template” template.

Note that the order in which you define the template is important. You must define the text/x-template tag before you reference it in the Vue.component constructor.

Registering a Component: Within a JavaScript File

The example below registers a <custom-note></custom-note> component and defines a prop (title) that can be passed in to the component. It also sets up validation on the prop - which returns a helpful error if the script runs in development mode.

Vue.component('custom-note', {
  props: {
    title: {
      type: String,
      required: true
    }
  },
  template: `
    <div class="card">
      <h2 class="title">{{title}}</h2>
      <slot></slot>
    </div>
  `
})

new Vue({
  el: '#root',
})

A simpler way to define the prop:

Vue.component('custom-note', {
  props: ['title'],
  template: `
    <div class="card">
      <h2 class="title">{{title}}</h2>
      <slot></slot>
    </div>
  `
})

comments powered by Disqus