in Tutorials, Vue.js

Directives in Vue

This example uses directives in Vue. To begin with learning directives, start by creating a new folder vue-directives. 

Directives serve as one of the primary ways, the user interacts with the view. Be it web view or mobile view.

In this example, we will create an element and on hovering over the element, we will display a random number. 

To achieve this, we will continue with the index.html from the first part. Create an index.html in the vue-directives folder and add the following code. Comments in the code explain what is what.

<html>
	<head>
		<!-- just any other regular html tag -->
		<title>Vue Demo App with Directives</title>
		<!-- Fetch vue.js from the following library -->
		<!-- Other alternatives are to download the original library from https://vuejs.org/ -->		
		<script src="https://unpkg.com/vue"></script>
		<style>
			/*
			Some styling to make Hello World look better.
			 */
			#app {
			  font-family: 'Montserrat', Helvetica, Arial, sans-serif;
			  -webkit-font-smoothing: antialiased;
			  -moz-osx-font-smoothing: grayscale;
			  text-align: center;
			  color: #2c3e50;
			  margin: 20px;
			  font-size:26px;
			}
		</style>
	</head>
	<body>
		<!-- 
			Element to play around using vue. 
			"app" is used in the javascript written below to add text and perform relevant actions.
		-->
		<div id="app">
			<!-- 
				v-bind is used to bind data to the div/element being targeted. In this example, the title tag gets altered to the random number being generated which is why, v-bind:title is used.

				To alter class to active or inactive, we can use v-bind:class. 

				Similarly to add a complete style to an element, we use v-bind:style
			-->
			<div v-bind:title="randNum">
				Hover over me for a random number
			</div>
		</div>
		<script>
			//app is assigned to the Vue instance. 
			//Vue accepts el and data to target the div. 
			var app = new Vue({
				el: "#app",
				data: {
					/* Math.random will give us a decimal which is then multiplied with 50 and then Math.floor will give us a rounded integer. To make it 1-50 instead of 0-49, I am adding a +1 at the end. */
					randNum: Math.floor(Math.random() * 50) + 1
				}
			});
		</script>
	</body>
</html>

Save the code and run it to see the random number being generated and shown to you on hovering the element.

0