Vue Practice - Form Test
Use the Vue Playground project for this activity (the one we created in class).
Make sure to look at the Vue code that you've already written to help you through this activity.
Add a component to the views folder named FormTest.vue. Then paste this code into it:
<template>
<h1>Test Form</h1>
<form>
<label>Name:</label>
<input type="text">
<br>
<label>Favorite Color:</label>
<select>
<!-- create OPTION elements with a v-for loop -->
</select>
<br>
<label>Check if you like pizza:</label>
<input type="checkbox">
<br>
<input type="submit" value="SAVE">
</form>
</template>
Set up a route that leads to the component, you can set the path to /form-test and set the name to form-test. Add a router-link to App.vue that allows users to navigate to the FormTest component.
Run the app and make sure the routing works.
Add a SCRIPT element to the FormTest component and inside the element, export the 'options' object (you may have to look a the code in another Vue component to remind you of how to do this).
Now, in FormTest.vue, Add the following data members:
- name (initialize it to an empty string)
- likesPizza (initialize it to false)
- favoriteColor (initalize it to an empty string)
- colors (initialize to an array like this: ["Red","Blue","Yellow","Green"]
Populate the SELECT element by using v-for to loop through the colors array and generate on OPTION element for each color in the the colors data member. NOTE: when you use the v-for directive, you will be required to bind the key attribute to a unique value. You can use the current string in the loop for this.
Use v-model to set up two-way databinding for the name, likesPizza, and favoriteColor data members.
Add an event handler method for when the form gets submitted. Make sure to prevent the default behavior (you could do this the 'Vue way' by using the prevent modifier, or you could use the preventDefault() method).
In the body of the event handler method, simply console log the name, likesPizza, and favoriteColor data members.
Possible/Optional Follow Up Activities:
- validate the user input
- emit the data members to a parent component (it's a little weird having App.vue listen for events when you are using a router, but it can be done and there are examples of how to do it on the internet.)
- bind an array of objects to the SELECT element (instead of an array of strings)
- add other types of INPUT elements to the form, such as a group of radio buttons, and bind data to them.
- install Bootstrap into the project, and then Bootstrap the form
- what else??