Creating a Component in a Project

Published on May 3, 2017 by

It’s time to open up a project like the one that we created in a previous post. In this post, I want to add a global component to the project, but first I will start out by cleaning the project up a little and remove some of the default stuff that was included with the template.

Replace the contents of the App.vue file with the following.

<template>
	<div class="container">
		<div class="row">
			<div class="col-xs-12">
				<announcement></announcement>
			</div>
		</div>
	</div>
</template>

<script>
   export default {

   }
</script>

Next, we will add an Announcement component that we referenced within the above template. So I want to add a component for displaying an announcement on the page. For this, I will add an Announcement.vue file with the following content.

<template>
	<div class="alert alert-info">{{ announcement }}</div>
</template>

<script>
	export default {
		data() {
			return {
				announcement: ‘The site will go down for maintenance soon!'
			};
		}
	}
</script>

Notice that I used an ES6 function above for the data function.

Now that we have our component ready, let’s register it globally within the main.js file.

import Announcement from './Announcement.vue';

Vue.component('announcement', Announcement);

Since we have already added an announcement tag within the App.vue file’s template, we are all set. If we needed to render a component more than once, we could simply add the v-for directive to it, for instance.

If you run the development server by running npm run dev, then you should see the announcement being displayed in the browser.

One thing we didn’t do, was to add a local component. Let’s do that next.

Featured

Learn Vue.js today!

Take an online course and become an Vue.js champion!

Here is what you will learn:

  • How to build advanced Vue.js applications (including SPA)
  • How Vue.js works under the hood
  • Communicating with services through HTTP
  • Managing state of large applications with Vuex
  • ... and much more!
Vue.js logo
Author avatar
Bo Andersen

About the Author

I am a back-end web developer with a passion for open source technologies. I have been a PHP developer for many years, and also have experience with Java and Spring Framework. I currently work full time as a lead developer. Apart from that, I also spend time on making online courses, so be sure to check those out!

Leave a Reply

Your e-mail address will not be published.