Getting Started with Vue.js: Lesson 12 of 25

Vue Events: Building a Crazy Button

Up Next

Vue Events: Building an Accordion

Autoplaying in 7 seconds!

Cancel

Let's use Vue to do a technique that is completely not practical! We're going to make it near impossible for our users to click on a button.

We'll use Vue to listen for the mouseenter DOM event. We'll then generate a random number and apply those numbers to the button styles.

Vue makes all the above very easy since all we have to do is update data and Vue will handle changing the template and HTML to reflect those changes.

Table of Contents

    The HTML

    We'll have a quick button:

    <div id="app">
        <a 
            class="button is-info is-crazy" 
            :style="buttonOffsets" 
            @mouseenter="moveButton">
                Catch me if you can!
        </a>
    </div>

    Here we are binding an object to the element's styles. We are also listening for the mouseenter event and then calling a moveButton method whenever that happens.

    The Vue JavaScript

    We'll be using Math.random() from Javascript's Math object to generate a number between 0 and 1. We'll also grab the window's height using window.innerHeight.

    const app = new Vue({
        el: '#app',
        data: {
            buttonOffsets: {
                top: null,
                left: null
            }
        },
        methods: {
            moveButton: function(e) {
                this.buttonOffsets = {
                  top: `${Math.random() * window.innerHeight}px`,
                  left: `${Math.random() * window.innerWidth}px`
                };
            }
        }
    });

    Chris Sevilleja

    173 posts

    Founder of Scotch.io. Google Developer Expert in Web Technologies. Slapping the keyboard until something good happens.