Tag Archives: Race

Creating a Running Game in VueJS – Part 2 – Components

This is the second post in a series that started here. If you’d like some context, then please visit the first post. In this post, I’ll be refactoring the small amount of code that we currently have, into Vue Components.

You can find the code for this post here.

Refactoring into Global Components

Let’s start with a very simple component, and that’s the display of “Seconds Remaining”. For the time being, we’ll create this in the same file, so all we’re doing here is shuffling code around. Instead of the following code:

<p>{{ secondsRemaining }}</p>

We’ll add this:

<div id="app">
    <div v-bind:style="location"></div>
    <seconds-remaining 
        v-bind:seconds="secondsRemaining">
    </seconds-remaining>            
</div>

A quick note on this, you may see the following syntax:

<div id="app">
    <div v-bind:style="location"></div>
    <seconds-remaining 
        :seconds="secondsRemaining">
    </seconds-remaining>            
</div>

Essentially, here the v-bind is implicit. Both work.

We can then define this inside the script tag like so:

<script>
    Vue.component('seconds-remaining', {
        props: ['seconds'],
        template: `
            <p>Seconds remaining: {{ seconds }}</p>
        `
    });
    new Vue({

    . . .

You’ll notice the use of the back-tick (`); you need this if the template spans multiple lines (in our case, we could probably get away with a single line – if we had, it would look like this:

<script>
    Vue.component('seconds-remaining', {
        props: ['seconds'],
        template: '<p>Seconds remaining: {{ seconds }}</p>'        
    });
    new Vue({

    . . .

One other important thing to note here, you are not permitted to have uppercase characters in the component name. You won’t get an error as such, it just automatically lower cases all the text, meaning that it won’t find your component (and you won’t know why!)

Let’s move the player into a component, too:

<div id="app">
    <player
        v-bind:location="location">
    </player>
    <seconds-remaining 
        v-bind:seconds="secondsRemaining">
    </seconds-remaining>            
</div>

And the script:

<script>
    Vue.component('seconds-remaining', {
        props: ['seconds'],
        template: `
            <p>Seconds remaining: {{ seconds }}</p>
        `
    });
    Vue.component('player', {
        props: ['location'],
        template: `
            <div v-bind:style="location"></div>
        `
    });

    . . .

In the next post, we’ll move these components out into their own files, which will involve actually installing Vue, rather than just importing the library.

References

https://www.taniarascia.com/getting-started-with-vue/

Vue.js Tutorial From Scratch – e07 – NPM, Webpack & Single File Component