In this article, we will look at how to use the v-bind
directive to assign values to the href
attribute.
Let’s begin by writing a simple index.html that will contain an anchor tag for us to work with. We will be making use of Vue.js cdn in this example.
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
Html code:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<title>Vue.Js</title>
</head>
<body>
<div id="app">
<a href="">Google</a>
</div>
</body>
</html>
Let’s create a new application instance using createApp()
function in the same file inside a script tag.
<script>
const { createApp } = Vue;
createApp({
data() {
return {
siteName: "Google",
};
},
}).mount("#root");
</script>
The entire index.html file should now look like this:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<title>Vue.Js</title>
</head>
<body>
<div id="app">
<a href="">{{siteName}}</a>
</div>
</body>
<script>
const { createApp } = Vue;
createApp({
data() {
return {
siteName: "Google",
};
},
}).mount("#app");
</script>
</html>
Let’s create a url
property that will hold the URL of the site that we want the user to visit once the link is clicked.
createApp({
data() {
return {
siteName: "Google",
url: "https://www.google.com",
};
},
}).mount("#app");
Now to use this property in our HTML template, we cannot simply write the property name using the curly brackets.
// ❌ Does not work
<a href="{{url}}">{{ siteName }}</a>
We need some way to bind the property to the href attribute. This is where v-bind
comes into the picture.
// ✅
<a v-bind:href="url">{{ siteName }}</a>
v-bind
binds the value of property url
inside the href property.
The entire index.html file should now look like this:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<title>Vue.Js</title>
</head>
<body>
<div id="app">
<a v-bind:href="url">{{siteName}}</a>
</div>
</body>
<script>
const { createApp } = Vue;
createApp({
data() {
return {
siteName: "Google",
url: "https://www.google.com",
};
},
}).mount("#app");
</script>
</html>
You can also use the shorthand for v-bind
.
// Shorthand
<a :href="url">{{siteName}}</a>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<title>Vue.Js</title>
</head>
<body>
<div id="app">
<a :href="url">{{siteName}}</a>
</div>
</body>
<script>
const { createApp } = Vue;
createApp({
data() {
return {
siteName: "Google",
url: "https://www.google.com",
};
},
}).mount("#app");
</script>
</html>