How to Create a Random Array Picker with Vue for Beginners
March 21, 2019 By Spenser Peiffer, aka Snazzy BoiThis is a simple tutorial/exercise for anyone starting out in Vue who doesn’t have the strongest knowledge base when it comes to JavaScript. You’ll want to know some JS, HMTL, and CSS for this, but you don’t have to be an expert – a novice understanding will suffice. The goal for the random array picker is to have an array of items and a button where, every time you click the button, you get a randomly chosen item from the array. Consider this your introductory guide on how to create a random array picker with Vue for beginners:
1. The Initial Setup
Running this project in CodePen is a great way to keep things as simple as possible. So, go to CodePen and open up a new pen. Next, go to the JS panel and click the gear icon. Go to the CDNjs search field and type “Vue”.
Vue should be the first result. Select it and then hit “Save & Close” in the top right. You can also do the same for CSS and set it to SCSS or whatever you like to use, but this isn’t necessary.
2. The HTML
For our little randomizer app, we don’t need a ton of markup. For now, we can just write up the scaffolding in plain static HTML. Just be sure to wrap everything inside of an element called “#app”. This will look something like:
<div id="app"> <p>Name</p> <button>Choose!</button> </div>
3. The Styles
The styles can be whatever you want. Again, in the interest of keeping this simple, we can keep this brief with something like:
body { width: 100%; min-height: 100vh; display: flex; justify-content: center; align-items: center; background: #f7f7f7; font-family: 'Montserrat',sans-serif; font-weight: 500; color: #000; } #app { min-width: 400px; height: 400px; border-radius: 20px; display: flex; justify-content: center; align-items: center; flex-direction: column; background: #fff; box-shadow: 0 1px 5px rgba(68, 68, 68, 0.5); } p { font-size: 2em; text-align: center; color: #EF5350; } button { border: none; background: #EF5350; color: #fff; text-transform: uppercase; font-size: 1.5em; padding: 10px 20px; border-radius: 10px; cursor: pointer; box-shadow: 0 1px 5px rgba(68, 68, 68, 0.5); }
If you want, you could also do this styleless. It’s up to you what your array picker looks like, but sometimes it’s just nicer to work with something that looks good.
4. The Vue
This is where we’ll get into the main “venVue” (the main venue? Get it?).
1. Make a Vue Instance and Give it an “Element”
To start out, we will need to make a Vue instance and give it an element or “el”, which, in this case, will be “#app”.
new Vue({ el: "#app" });
Now, Vue knows to watch #app and that everything inside this Vue instance has to do with everything inside of #app.
2. Make a “Data” Object
Next, we will make “data”. Data is, in a way, a list of all your DOM-relevant variables. If it is something that is being set at some point, something that will be printed out in the DOM, or really anything globally relevant within that Vue instance, it should be in the data object along with its value – even if it’s an empty string.
In this case, we will have an object for the array we will be picking from and a string where we will put the chosen item. For this array of items, we will use a list of some random names. It should end up looking something like this:
new Vue({ el: "#app", data: { list: ['Ashley','Andy','Andrew','Chad','Hiep','Sarah','David'], chosenName: '' } });
3. Make the “Methods” Object
Now that everything is all in place, we can do some actual logic. After the data object, put a comma and then make the “methods” object. “Methods” is where your functions will live.
There are other objects, like “Computed”, that are similar, but, in the interest of keeping this simple, we will skip those today. Vue’s documentation is pretty good, so you can always go back and reference that if you need to. Within the “method” object, we will make a function called “picker()”. Using everything we have done so far, it should look something like this:
new Vue({ el: "#app", data: { list: ['Ashley','Andy','Andrew','Chad','Hiep','Sarah','David'], chosenName: '' }, methods: { picker: function(){ } } });
4. Create a “chosenNumber” Variable
Within the function, a lot of the code will actually just be plain ol’ vanilla JavaScript. Make a variable called “chosenNumber”. This will be the array item number we will use to pluck a name from the array.
var chosenNumber = Math.random();
Let’s break this down: Math.random() will give us a random number between 0 and up to, but not including, 1, which could be a number like 0.8029369245277826.
5. Multiply by the Length of the Array
Next, we will multiply by the length of the array by referencing its length property, like so:
var chosenNumber = Math.random() * this.list.length;
“this.list” is our array from the data object (where we originally defined list as a property of the data object). As a note, whenever you are pulling from the data object put “this.” in front of it. It’s complicated and has to do with scope, but, for now, just know to never forget the this dot. Adding “.length” gets the number of items in the array. Now, it will spit out numbers like 4.8029369245277826.
6. Clean up the Numbers
This still isn’t quite what we want, so we need to get rid of all those numbers after the decimal. We can do this by adding “Math.floor” to the function, which will look something like this:
var chosenNumber = Math.floor(Math.random() * this.list.length);
“Math.floor” will take whatever number was given and will round it down to the nearest whole number. So, 4.8029369245277826 becomes 4.
7. Grab the Name of the “chosenNumber”
We now have our number, so let’s grab that name. We want to grab the name from the array and set it to “this.chosenName”. We can do this by referencing the name in that array by using the chosen number to represent an item’s index, like this:
this.chosenName = this.list[chosenNumber];
So, if “chosenNumber” is 4, putting it in those square brackets will pick item number 4 from the array. It’s important to remember that arrays start at 0, so it’s really the 5th item. And, that’s it for the logic!
Recap of the Code for the Vue Instance
To recap, our function “picker” pulls in the array from the data, picks a random number, uses that number to grab a name from the array, and then sets that name as “chosenName”. All the code so far should look something like this:
new Vue({ el: "#app", data: { list: ['Ashley','Andy','Andrew','Chad','Hiep','Sarah','David'], chosenName: '' }, methods: { picker: function(){ var chosenNumber = Math.floor(Math.random() * this.list.length); this.chosenName = this.list[chosenNumber]; } } });
5. Get the Readout from the HTML
Now, all that’s left is to go back to the HTML so that we can get the readout.
1. Add “@click”
First things first, go to the button and add this:
<button @click="picker">Choose!</button>
The “@click” will listen for the button to be clicked and, when it is, it will run whatever is in the double quotes. In this case, it’s going to run the “picker” function we completed previously. “@click” is the shorthand way to define your directive and is equivalent to “v-on:click”.
2. Add “chosenName”
Next, in the paragraph tag, we’ll use the default Mustache syntax to indicate where we want this to display, referencing the property from our data object by doing this:
<p>{{chosenName}}</p>
“chosenName” here is bound to the “chosenName” property in the data object. So, whatever “chosenName” is set to in the data object, will be output to wherever its called in the HTML part of the app. In our case, it will put the name.
Recap of the Code for the HTML
To recap, here is all of the HTML for this part:
<div id="app"> <p>{{chosenName}}</p> <button @click="picker">Choose!</button> </div>
And that’s it! It should work. If you need to play around a bit more to understand it, here is our CodePen version. Feel free to fork it, poke it with a stick, and play around.
See the Pen
Vue Randomizer by Spenser (@Spenser_Peiffer)
on CodePen.
This is one way to build a random array picker with Vue. Take a look at how to create a random array picker with Svelte if you want to try it in something else.
View Comments