What is the best way to create router links on the fly in Vue.js?

I am currently exploring how to achieve 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>

The messages property contains an array of objects, each with an id property that I aim to append to the "to" attribute. If there are two items in the messages array with ids 1 and 2 respectively, the expected result would be:

<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 attempted using {{ message.id }}, but this resulted in an interpolation error. How can I display the actual value for message.id in the "to" attribute? The item.name attribute displays correctly.

Answer №1

To make it work, ensure to include 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>

If you omit v-bind:, you will be treating 'user' + item.id as a literal string value. For further insights, refer to this section of the documentation

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered in TypeScript's Map class

When working with TypeScript, I keep encountering an error message that reads "cannot find name Map." var myMap = new Map(); var keyString = "a string", keyObj = {}, keyFunc = function () {}; // assigning values to keys myMap.set(keyString, "val ...

Creating an uncomplicated search bar that dynamically adjusts values based on its function

Summing it up, there is a div situated within my app.component.html: <div class="col-lg-6 search-div"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search for..."> <span class="input-group-b ...

Converting string patterns to regular expressions

I am utilizing mongodb to store data. My requirement is to save complete regular expressions as strings: { permissions: [{ resName: '/user[1-5]/ig', isRegex: true }] } Although I am aware of the existence of the module mongoose-rege ...

Tips on aligning the height of the vertical 'b-tabs' navigation section with the content section based on the content's height

I am trying to retrieve the value of max-height from a different source (such as vue data:) and then apply it to the navigation section of the b-tabs. I understand that I can create a CSS class and assign it to nav-class in order to modify the style of the ...

Increasing the maximum width of an image in CSS is necessary to see the max-height take effect

Within my HTML structure: <Col md="6"> <div className="hero-section"> <div className={`flipper ${isFlipping ? "isFlipping" : ""}`}> <div className="front"> <div className="hero-section-content"> ...

Triggering an event through a shared messaging service to update the content of a component

I'm looking for a simple example that will help me understand how I can change the message displayed in my component. I want to trigger a confirmation box with *ngIf and once I confirm the change, I want the original message to be replaced with a new ...

Utilize HTML strings to serve static files in express.js

While I primarily focus on frontend development, I often face challenges when working on the server side. Currently, I have a server.js file that includes: const express = require('express'); const http = require('http'); const path = ...

Is it possible to use jQuery to load an HTML file and extract its script?

I have a navigation bar with five buttons. Whenever a button is clicked, I want to dynamically load an HTML file using AJAX that includes some JavaScript code. The loaded file structure resembles the following: <div> content goes here... </div& ...

Guide to successfully passing a function as a prop to a child component and invoking it within Vue

Is it really not recommended to pass a function as a prop to a child component in Vue? If I were to attempt this, how could I achieve it? Here is my current approach: Within my child component - <template> <b-card :style="{'overflow-y&apo ...

Node.js removes leading zeroes from dates

I am looking to generate a string with the current date and time in the format: "2021-06-02 09:37:38" const today = `${new Date().toLocaleDateString('sv-se')} ${new Date().toLocaleTimeString('sv-se')}`; console.log(today); ...

Removing nested divs using JavaScript

My website has a nested div structure which contains multiple child divs. Here is an example of the div structure: <div id="outside-one"> <div class="inside" id="1"></div> <div class="inside" id="2"></div> <div ...

What is AngularJS global data binding?

My template has a dynamic title that is inserted using the following code: <title>{{title}}</title> For each of my pages/routes, I use a different controller where I define the title like this: BackyApp.controller('HomeController', ...

Is your webpage slow to respond after a page-refresh? (Delayed HTML rendering causing lag)

Whenever I adjust the screen size to that of a phone or any device smaller than 768px, the search bar doesn't display in its proper position until the page is refreshed. It should be correctly placed right from the start. Furthermore, when I resize th ...

Creating a Dual Y-Axis Chart with Two Sets of Data in chart.js

I utilized the chart.js library to write the following code snippet that generated the output shown below. My primary concern is how to effectively manage the labels on the horizontal axis in this scenario. CODE <!DOCTYPE html> <html lang="en"& ...

Dockerfile unable to recognize environment variable

I'm currently working on a Vue application running with Docker, and I want to use environment variables to target specific project repos. However, when I try setting the env variables, they don't seem to be recognized in the Dockerfile. Can you ...

Alert: Unauthorized hook call and Exception: Cannot access properties of null (reading 'useState')

I am currently working on a project using ASP.NET Core with React. To bundle my code, I have opted to use Webpack 5. Within the index.jsx file, I have the following code: import { useState } from "react"; function App() { const [value, setV ...

Using Typescript to Import One Namespace into Another Namespace

Is it possible to export a namespace from one typescript .d.ts file and then import that namespace into another .d.ts file where it is utilized inside of a namespace? For instance: namespace_export.d.ts export namespace Foo { interface foo { ...

Scrolling with React Event

I am attempting to create a scrollbar that only appears when I scroll within a particular area using React. I am utilizing debounce and useState in my implementation. The issue: When I reach the end of the scroll, the event continues to repeat indefinitel ...

I specified Authorization Bearer in the Fetch API configuration, however, the Request Headers do not contain the necessary Authorization information

Check out the following code snippet: fetch('http://localhost:3000/tasks/', { method: 'GET', mode: 'no-cors', headers: new Headers({ 'Authorization': 'Bearer <jwt_token>' ...

Issue arising from background change upon component focus

My component needs to change its background color when focused, but for some reason it's not working. The hover effect works fine, but the focus doesn't. Can anyone assist me with this issue? import { CardContainer } from './styles' in ...