site icon

Hi, I’m Chris

I am a web developer teaching
regular people how to code

~ Welcome to my blog ~

Binding a dynamic value to a href with Vue.js

Links are very important in any web app to navigate to different sections, pages or even external pages too.

In Vue.js, we can create as simple link like this:

<template>
  <a href="/account">My account</a>
</template>

We often want to add a variable into this link too, such as the current user id.

Let's imagine we had the current user stored as a data property:

<script>
export default {
  data() {
    return {
      user: {
        id: "123",
        name: "Chris"
      }
    };
  }
};
</script>

We may want to navigate to a dynamic URL such as "mydomain/user/123/account".

In this URL, the user id of 123 is the dynamic part which will change depending on the logged in user.

The first step to allow the href to receive a dynamic value, is to use the v-bind directive.

V-bind is used to reactively update our HTML attribute, and looks like this:

<a v-bind:href="/account">My account</a>

// or shorthand version:
<a :href="/account">My account</a>

This current example will throw an error. This is because we are passing in a string of /account.

While this is perfectly fine with a regular href, using v-bind means we need to pass in a Javascript expression.

If you are unsure of what a Javascript expression is, from the Mozilla Developer Network:

An expression is any valid unit of code that resolves to a value.

Basically this means we need to pass in some Javascript which will result in a valid URL to link to.

In it's most simple form, this could just be a variable like this:

<a :href="user.id">My account</a>

// links to mydomain/123

If we wanted to take this further, and link to "mydomain/user/123/account", we would need to approach it just like how we would add any variable into a string using Javascript.

By using concatenation. We convert the above URL to be 'user/'+user.id+'/account', and we pass it into the link (still inside of the double quotes):

<a :href="'user/'+user.id+'/account'">My account</a>

// links to mydomain/user/123/account

This can also be converted to use template literals if you prefer:

<a :href="`user/${user.id}/account`">My account</a>

// links to mydomain/user/123/account

If using Vue Router or NUXT, using declarative navigation, the same principles also apply to adding dynamic links, but here we bind the "to" property:

<!-- Using vue router: -->
<router-link :to="`user/${user.id}/account`">My Account</router-link>

<!-- Using Nuxt -->
<nuxt-link :to="`user/${user.id}/account`">My Account</nuxt-link>

// both link to mydomain/user/123/account

- By Chris Dixon

Chris Dixon is a web developer and teacher. Teaching thousands of students mainly in Vue.js React.js, WordPress and web development.