VI. Vue.js and Coldfusion: Forms, if/else

If you're just getting started with this series of Vue.js posts, you should start with the Vue.js Starter Page.

In this Vue.js post I'll continue with forms but also introduce you to conditional rendering using the v-if/v-else/v-else-if directives. Yes, Vue.js will allow you to set up conditional code to view/display/execute other page elements based on conditional logic. It follows the basic conventions of other programming languages and is really easy to use.

Take a Look

  • Don't forget the Vue.js library reference in the script tag on line 4....
  • ... and line 9 is pretty important too.
  • Finally, you have to add a sportInterests data element to the Vue.js data object in the Vue.js instance (see code below).

Let's Tie It All Together

In the last post we looked at a similar form as the one below, where we built an array for the sportInterests value to be dynamically displayed when the user checked the corresponding checkbox. We displayed the selected values by using the join() method on the named data set (sportInterests) and everything worked nicely. Now let's look at what happens to the user experience when we add some conditional rendering using v-if/v-else/v-elseif.

Sport Interests
Goalie
Forward
Winger


Yikes! You made too many selections, take it easy!

Your selected sport interests include: {{sportInterests.join(', ')}}

Please select at least one sport interest.

<!doctype html>
<html>
<head><meta charset="UTF-8"><title>VueJS</title>
<script src="https://unpkg.com/vue@2.3.0"></script>
</head>
<body>

<div id="app">
	<form>
		
		<fieldset>
			<legend>Sport Interests</legend>
			<div>
				<input type="checkbox" value="Goalie" v-model="sportInterests">Goalie
			</div>
			<div>
				<input type="checkbox" value="Forward" v-model="sportInterests">Forward
			</div>
			<div>
				<input type="checkbox" value="Winger" v-model="sportInterests">Winger
			</div>
			<input type="submit" value="Register"><br><br>
			
			<!--<p>Your selected sport interests include: {{sportInterests.join(', ')}}</p>-->
			<!--
			You can also use the "v-if" directive instead of "v-show", which will completely remove the element from the DOM when the expression is false.
			"v-else" can be used immediately after "v-if" (just like an if/else statement)
			-->
			<p v-if="sportInterests.length==3">Yikes! You made too many selections, take it easy!</p>
			<p v-else-if="sportInterests.length > 0">
				Your selected sport interests include: {{sportInterests.join(', ')}}
			</p>
			<p v-else>Please select at least one sport interest.</p>
		</fieldset>

	</form>	
</div>

<script>
	var vm = new Vue({
		el:'#app',
		data: {
			newEmail: 'rich@cfsnap.com',
			sportInterests: []
			
		}
	})
</script>

</html>

Link your website to this page! Copy and paste the URL below:
http://www.cfsnap.com/vue-js/vue-js-coldfusion-forms-part-2/