0

When to use vue-router link as

<router-link to="/login">Login</router-link> it render to login view and <router-link :to="/login">Login</router-link> this one is the same.

What is the difference and why we use the colon and we must use it ?

Hanik
  • 317
  • 2
  • 6
  • 25

2 Answers2

2

The : is v-bind Shorthand syntax. https://v2.vuejs.org/v2/guide/syntax.html#v-bind-Shorthand

If you want to use Javascript expressions then need to use :


let LoginUrl = '/login'

<router-link :to="loginUrl">Login</router-link>


// Another example

let student = {id: 521, name: 'Jhon Doe'}

<router-link :to="`students/${student.id}`"></router-link>

Without : You're just writing string inside to=""

tony19
  • 125,647
  • 18
  • 229
  • 307
Awolad Hossain
  • 1,007
  • 13
  • 18
1

Colon is shorthand for v-bind directive and you would use it to bind to computed property or method.

https://v2.vuejs.org/v2/guide/syntax.html#v-bind-Shorthand

Examples:

<!-- Static value -->
<router-link to="/login">Login</router-link>

<!-- Dynamic values-->
<router-link :to="`/user/${id}`">Login</router-link>
<router-link :to="getUserLink(id)">Login</router-link>
<router-link :to="currentUserLink">Login</router-link>

new Vue({
    data() {
        return {
            id: 1
        }
    },
    computed: {
        currentUserLink() { return '/user/'+ this.id }
    },
    methods: {
        getUserLink(id) {
            return '/user/'+ id
        }
    }
});
Edin Omeragic
  • 1,948
  • 1
  • 23
  • 26