How to Create a Component in Vue 2.1

  Programming

I’ve been using Vue.js for a while now, and recently thought it’s time I learned Vue 2.x. So, I decided to create a simple Reddit component—one that can display recent posts from any subreddit—using Vue 2.1. Why? Well, what better way to learn a framework than to create something interesting with it. In this tutorial, I’ve documented the steps that I took to create it.

To be able to follow this step-by-step tutorial, you’ll need:

  • Node.js v6.7.0 or higher
  • A basic understanding of JavaScript

1. Project Setup Using Vue CLI

Vue has a very handy CLI you can use to quickly set up a new project with all the right dependencies. Here’s how you can install it globally:

npm install -g vue-cli

The CLI offers several starter templates. In this tutorial, we’ll be creating our project using a template based on Browserify and Vueify.

vue init browserify-simple my-reddit-app
cd my-reddit-app

Once the project has been generated, I suggest you install all its dependencies first.

npm install

To fetch data from Reddit’s servers, we’ll be using Axios, a very powerful and easy-to-use HTTP client. Therefore, add it is as a dependency.

npm install -S axios

At this point, our project has been set up.

2. Component Creation

If you enter the src directory of your project, you’ll see that it already has two files. We’ll be writing most of our code inside App.vue, a single file containing all the layout, logic, and styling of our app. It already contains some code we don’t need. Therefore, I suggest you empty its contents. Here’s an easy way to do so from the command-line:

rm -f App.vue
touch App.vue

And now, open App.vue using your favorite code editor.

Step 1: Create the Layout

Our component’s layout is going to be very simple. It will contain one heading mentioning the name of a subreddit, and one unordered list containing all its posts.

Here’s the layout I’ll be using:

<template>
  <div class="reddit-list">
    <h3>Posts from /r/{{ subreddit }}</h3>
    <ul>
        <li v-for="post in posts">
            <a v-bind:href="post.data.url"> 
                {{ post.data.title }}
            </a>
        </li>
    </ul>
  </div>
</template>

As you can see, I’m using the mustache syntax for interpolating a few variables. I’m also using the v-bind and v-for directives. The v-for directive is, of course, being used to loop through all the posts of the subreddit. I’ve used the v-bind directive to initialize the value of href because we can’t use mustache syntax inside an attribute.

Step 2: Add Styles

Adding styles is optional. And really, there’s hardly anything new to learn here if you already know CSS.

<style scoped>
    .reddit-list {
        font-family: sans-serif;
        width: 500px;
        padding: 10px;
        background: #f1f2f3;
        border: solid 2px #ccc;
    }            
    .reddit-list h3 {
        font-size: 15px;
        font-weight: bold;                
    }
    .reddit-list ul {
        font-size: 13px;
        list-style-type: none;
        padding: 0;                
    }
    .reddit-list ul li {
        margin-bottom: 10px;
    }
</style>

If you are wondering why the <style> tag has a scoped attribute, it is to ensure that the styles are applied to the component only, and not globally.

Step 3: Add Code

It’s now time to write some JavaScript code. Therefore, start by adding a <script> tag.

<script>
</script>

The first thing we’re going to do now is initialize Axios.

let axios = require('axios');

Next, we’re going to specify that the component shall have two properties: subreddit and limit. subreddit will, of course, contain the name of a subreddit, and limit will specify the number of posts to fetch.

The component shall also have an array of posts as its data.

We’ll be fetching the posts from Reddit once the component has been mounted. As you might’ve guessed, we’ll be using Axios’s get() method to do so. Once the data has been fetched from Reddit’s servers, we’ll use it to initialize the posts array.

Accordingly, add the following code:

export default {
    data () {
        return {
            posts: []
        }
    },
    props: ['subreddit', 'limit'],
    mounted: function() {
       let self = this;   
       axios.get("https://www.reddit.com/r/" + this.subreddit + "/.json?limit=" + this.limit)
            .then(response => {
                  self.posts = response.data.data.children;
            });        
    }
}

The component is now ready to be used.

3. Using the Component

In the previous step, you saw that our component has two properties: subreddit and limit. We need to set the values of those properties before we use the component. We can do that inside the main.js file.

All you need to do is pass an extra JSON object while creating the component. Therefore, update the render function so that it looks like this:

render: h => h(App, {props: {subreddit: 'javascript', limit: 10}})

And that’s it. You can now view your component in action by simply running the project.

npm run dev

The above command should automatically open a new browser window for you showing you the component.

Vue 2.1 Component

Conclusion

In this tutorial, you learned how to, in a matter of minutes, create and use a simple component using Vue 2.1.

If you found this article useful, please share it with your friends and colleagues!