Dave
Dave

Reputation: 2591

How can you dynamically build router-links in Vue.js?

I am trying to do the following in Vue.js

     <table>
        <tr v-for="item in messages">
            <td><router-link to="'/user/' + item.id">{{ item.name }}</router-link></td>
        </tr>
    </table>

My messages property has an array of objects in it. Each object has an id property, which I want to be appended on to my to attribute. So if I had two items in the messages array with ids of 1 and 2, I would expect to get something like this:

     <table>
        <tr v-for="item in messages">
            <td><router-link to="/user/1">{{ item.name }}</router-link></td>
        </tr>
        <tr v-for="item in messages">
            <td><router-link to="/user/2">{{ item.name }}</router-link></td>
        </tr>
    </table>

I also tried putting doing {{ message.id }}, but that gives me an interpolation error. How can I get this to render the actual value for message.id in the "to" attribute? The item.name attribute renders as expected.

Upvotes: 2

Views: 1689

Answers (1)

AldoRomo88
AldoRomo88

Reputation: 2076

Just add v-bind: before to

<table>
    <tr v-for="item in messages">
        <td><router-link v-bind:to="'/user/' + item.id">{{ item.name }}</router-link></td>
    </tr>
</table>

Without v-bind: you're literally using 'user' + item.id as value. For more clarification check this docs section

Upvotes: 3

Related Questions