II. Vue.js Directives: v-bind

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

Vue.js will go a long way in helping your front end (especially form) development. It uses these things called Directives to allow you to act upon a DOM element, and these Directives are really easy to use. v-bind is a good one to start with, as it does pretty much what you'd think; it binds vue.js to a specific element on your web page.

Take a Look

In the code below you'll see a few things going on, allow me to explain:
  • Note the script tag on line 4, that references the Vue.js library so that it will work on your web page. This has to be present or Vue.js won't work.
  • <div id="app"> on line 7, and el:'#app' on line 14. This is how you tell Vue.js which DOM element to act upon; in this case we're telling Vue.js to act on the div called "app".
  • On line 9 you see an anchor tag (<a>) with the "v-bind:href..." attribute. Here is where the Vue.js mojo is happening: Vue.js "binds" the url attribute of the anchor tag with the url attribute of the Vue.js data object (line 16). I added the url param 'myParam' to show you how to append data to the url, hope it helps. This might seem a little long-winded for this simple demonstration, but trust me later on when we start doing bigger and crazier stuff the syntax will become very useful.

Try It!

... a slightly underwhelming example, but the link below will take you to Google. To get a better insight of what's going, try viewing the source code for this page, as well as try inspecting the link. If you open the browser's console window you can enter vm.url="http://www.disney.com" and hit enter, then mouse over the "Link to Google" text - and notice you've changed the url of the link.

<!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">
	<!--data binding: Have to use v-bind or the colon shorthand notation. v-bind is used below.... -->
	<a v-bind:href="url +'?myParam=1'">Link to Google</a><br>
</div>
</body>
<script>
	var vm = new Vue({
		el:'#app',
		data: {
			url: 'https://www.google.com'
		}
	})
</script>
</html>

Link your website to this page! Copy and paste the URL below:
http://www.cfsnap.com/vue-js/vue-js-directives-v-bind/