V-bind a Link With Vue.js

In Vue.js a developer can use curly braces {{ }} to interpolate data from the Vue controller onto their view pages. The problem with the curly braces is that they can only accept output that can be converted to a string. So strings and functions are all good inside these braces, but objects and certain HTML elements are not.

The href tag is one such element that cannot be used in curly braces. Enter v-bind a Vue.js directive. Directives are basically an instruction that’s placed in the code. V-bind is specifically used to pass data to the DOM.

(For this example I’m using an index.html file).

In your index.html file

<div id="app">
  <p>{{ greeting }}</p>
</div>

Below this is your script tags for your JavaScript logic

<script>
   new Vue({
     el: '#app',
     data: {
       greeting: "Hello World!",
       link: "https://jjprogramming.wordpress.com"
     }
  })
</script>

Here is how v-bind works.

In the script tags a new Vue instance has two objects stored in the data object. The first is an attribute called greeting which holds a string called”Hello World!”, and the second is an attribute called link which holds a link to this website.

In the HTML, greeting is interpolated with curly braces. If you were to attempt to dynamically bind the link attribute with those same curly braces, the text My Website would appear on screen like it was a fully functional link. That is until you click it, and get a 404 error.

<a href={{ link }}>My Website</a>

Since a href is an HTML element and not a string, this can not be interpolated. Instead v-bind must be used. V-bind binds attributes to the “data” in your new Vue instance. It then has access to all the methods and functions that you’ve created inside that instance. V-bind takes one argument, in this case it’s taking the argument href, and then the argument expects the attribute you wish to bind to it.

{{ title }} <a v-bind:href="link">My Website</a>

Your final output should look like this.

<div id="app">
 <p>{{ greeting }} <a v-bind:href="link">My Website</a></p>
</div>

<script>
   new Vue({
     el: "#app",
     data: {
       greeting: "Hello World!",
       link: "https://jjprogramming.wordpress.com"
     }
   })
</script>

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s