Creating a Component in a Project

This entry is part 55 of 55 in the series Vue.js: From Beginner to Professional

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.

Series Navigation<< Component Naming Conventions

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *