Vineet
Vineet

Reputation: 783

How to give dynamic URL in <router-link> in VueJS?

I am using v-for directive to get URL name. However, I am facing difficulty in passing the value obtained from a instance of v-for as URL name.

<template>
  <v-list-tile class="pl-5" v-for="choice in choices" :key="choice.name">
    <v-list-title-content>
      <router-link to="'/' + choice.name">
        <v-list-title-title class="white--text headline">
          {{choice.name}}
        </v-list-title-title>
      </router-link>
    </v-list-title-content>
  </v-list-tile>
</template>

<script>
export default{
  data(){
    return{
      choices:[
         name:'A',
         name:'B',
         name:'C',
         name:'D'
      ]    
    }
  }
}
</script>

Upvotes: 2

Views: 11288

Answers (5)

Varit J Patel
Varit J Patel

Reputation: 3520

Well, In order to make any attributes to dynamic, you need to use v-bind directive.

Short-hand property for v-bind is :

Hence you can use it as below

<router-link v-bind:to="'/' + choice.name">

With short-hand

<router-link :to="'/' + choice.name">

Official v-bind doc

Hope it helps!

Upvotes: 1

ssc-hrep3
ssc-hrep3

Reputation: 16069

You need to bind the choice name like any other variable property: Use v-bind:to or the shorthand form :to.

Here are the docs to v-bind: https://v2.vuejs.org/v2/api/#v-bind

You can also directly bind an object to the to directive, passing along the name of the route, so that you need to concat a path. Like this:

<router-link :to="{ name: 'choice1' }">Link</router-link>

Upvotes: 0

exoticism4869
exoticism4869

Reputation: 651

one tip:

when using v-bind like:

// Box.vue
<router-link id="box" :to="{ path: pathto }">{{ name }}</router-link>

don't do the fool thing like me as below:

<Box name="Frontend" pathto="/box/frontend" />
<Box />
<Box />

then you break down.

Upvotes: 0

GMKHussain
GMKHussain

Reputation: 4661

Example with Data():

<router-link :to="myURL">My Link</router-link>

export default {
    // ...
    data() {
        return {
            myURL: '/my-page-link'
        }
    }
    // ...
}

Example without data()

<router-link :to="/my-page-link">My Link</router-link>

Note: v-bind OR : before to attribute

Upvotes: 0

Radu Diță
Radu Diță

Reputation: 14171

You need to bind to. Try something like this

<router-link :to="'/' + choice.name">

Upvotes: 9

Related Questions