How to dynamically change the path of href in Vue.js

in Code Write a comment

In this tutorial, you’ll learn how to dynamically change the href value in Vue.js.

Let’s create a new Vue.js component that will render a list of products.

<div id="app">
  <h2>Products:</h2>
  <ul v-if="products.length > 0">
    <li v-for="product in products">{{ product.title }}</li>
  </ul>
</div>

Now, let’s create an array of products.

new Vue({
  el: "#app",
  data: {
    products: [
      { id: 1, title: "Hololens" },
      { id: 2, title: "Google Glass" },
      { id: 3, title: "PlayStation 5" }
    ]
  }
})

Each product has a unique ID. Let’s use it to create a dynamic link for each list item.


Hi, I'm Renat 👋

 


We’re going to re-write the HTML part an include an <a> tag.

<div id="app">
  <h2>Products:</h2>
  <ul v-if="products.length > 0">
    <li v-for="product in products"><a :href="'/products/' + product.id">{{ product.title }}</a></li>
  </ul>
</div>

Now, if you click on product title it will open an individual product page. The example above also shows how to concatenate href value in Vue.js/JavaScript.

If you find this post useful, please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/vue-js-href

PS: Make sure you check other Vue.js tutorials, e.g. useful Vue.js filtershow to upload a file in Vue.js and load external CSS file into Vue.js component.

Incoming search terms:

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment