Sorting Hat Project with Vue.js

This past Friday, we had our second all-day class assessment to build a Sorting Hat using the Vue JavaScript framework! I was really, really excited about the project. :)

I very quickly got the general design and layout up and running, and the general gist was to generate a random Hogwarts house for the user when they click the Sorting Hat on the page. I had a bit of a tricky time generating just one house on click, so I wanted to write out what I did for myself for future reference:

On the Sorting Hat image, I used the Vue directive v-on:click="sortMe()" to call the sortMe function. That function generates a random number between 0-3, each which correspond to one of the four Hogwarts houses that were listed out in a data object as a part of the Vue data. Generating that number was relatively easy with the code this.index = Math.round(Math.random() * (4 - 1));, and the index then correlates directly to one of the houses in the data object. Once the index was chosen, I created a Vue component that gives the user a message from the Sorting Hat, including the house name, house crest and short description about it.

The issue that I was having originally was that I was using a v-for directive to list out each house initially as a way to get something pulled in on the page. This commands Vue to loop through the entire Houses data object, and therefore it always printed out all four houses.

My last tip about Vue today is, when in doubt, always use this. in front of any computed, method or watch elements. It seems like you need them more often than not!

If you’re curious, you can view my project on Heroku here.