Tips for transferring information from an express rendering to a Vue component?

When working with an express route,

page.js

router.post('/results', (req, res, next) => {
    output.terms  = "hello"
    output.results = [{"text": "hello world"}, {"text": "hello sunshine"}]
    res.render("/myview",output)    
})

The code above successfully displays the text.

myview.pug

extends ../layout.pug

block content
    each result in results
        span=result.text

However, when attempting to use the following vue component, an error occurs stating TypeError: results is undefined

results-view.vue

<template lang="pug">
    li(v-for='result in results')
        span {{ result.text }}
</template>

<script>
    export default {
        ...
    }
</script>

myview.pug

extends ../layout.pug

block content
    results-view

If you are wondering how to pass data from the router to the vue component, it can be a bit trickier and may require additional steps.

Answer №1

At times, it can be beneficial to transmit data directly from the router to your frontend component without the need for an additional API call and fetching process.

const user = { id: '456', name: 'Max Johnson' }
res.render('user/profile', { user })

user/profile.pug

// This snippet will declare user as a global variable
script window.user= !{JSON.stringify(user)}

// The following code will execute in the browser
script.
  // This JavaScript code will be executed in the browser
  alert(`User : ${user.name}`)

Answer №2

It might be beneficial to consider an alternative approach. Sending data directly from a route to a component may not be the most efficient solution. One option is to set up an API endpoint that can provide the necessary data, which can then be easily accessed in Vue through a request.

Answer №3

Ultimately, this solution proved effective. While it may not adhere to best practices (I cannot say for certain), a commenter named serkan did provide a warning.

results-view.vue

<template lang="pug">
    li(v-for='result in results')
        span {{ result.text }}
</template>

<script>
    export default {
        name: 'results-view',
        props: ['results']
        ...
    }
</script>

myview.pug

extends ../layout.pug

block content
    results-view(results=results)

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

Angular pop-up message not displaying title or content

I have integrated the toaster directive into my AngularJS web project. Following the documentation, I have declared the container on my view as shown below. <toaster-container toaster-options="{'time-out': 3000, 'close-button':true ...

Ways to provide input parameters to a method upon clicking an element without using the HTML onclick attribute

Is there a way to pass data between pages without redirecting to the next.php page every time a button is clicked? One suggestion is to remove the onclick attribute from the button: <button class="submit-btn"></button> and use this jQuery fu ...

The React apexchart heatmap's height remains static despite attempting to change it through state updates

Seeking to dynamically resize the height of an "Apexcharts heatmap" based on server data. Despite attempting to manipulate code in various lifecycle methods, including componentDidMount() and where the data is received, I have not been successful. Within ...

working with Selenium in the Chrome web browser

Within a file named e2e.js, the following code was written: const webdriver = require('selenium-webdriver'); const driver = new webdriver.Builder().forBrowser('chrome').build(); driver.get('https://www.google.co.il/'); I h ...

Why is the error message "Invalid field name: '$conditionalHandlers' in 'collaborators..$conditionalHandlers'" popping up now?

Currently, in my Node/Express/Mongoose application (latest versions), I am working on a feature that involves "Projects" with a list of "collaborators" identified by the IDS of "Users". To simplify complex aggregations, I have decided to store these IDS as ...

How can I set a background image to automatically adjust to the width of the window, be full height, allow for vertical scrolling, and

How can I set a full-screen background image that adjusts to the body width without horizontal scrolling, maintains height proportionate to width, and allows for vertical scrolling? Here is my current code: html, body { margin: 0px; padding: 0px; } bo ...

Tips for preventing click events from interfering with execution in React

On my screen, there is a specific image I am looking to prevent all actions while a process is running. When I trigger the Execute button, it initiates an API call that can take 4-5 minutes to complete. During this time, I need to restrict user interacti ...

A method for reversing specific characters within lengthy strings

I'm currently tackling a coding problem: For a given string s and an integer k, the task is to reverse the first k characters for every 2k characters starting from the beginning of the string. If there are less than k characters remaining, reverse al ...

What impact does reselect have on the visual presentation of components?

I'm struggling to grasp how reselect can decrease a component's rendering. Let me illustrate an example without reselect: const getListOfSomething = (state) => ( state.first.list[state.second.activeRecord] ); const mapStateToProps = (state ...

Invalid file name detected during the download process

Below is the Javascript code I currently use to download a pdf: var link = document.createElement('a'); link.innerHTML = 'Download PDF file'; link.download = "Report.pdf"; link.href = 'data:application/octet-stream;base64 ...

Storing deeply nested objects in mongoose

Having a background in PHP/ MySQL, I am facing challenges when it comes to structuring and storing my data effectively. My goal is to develop a small application for adding recipes with multiple ingredients. I already have a set of pre-populated ingredien ...

Unpacking Reddit's JSON data in a Node environment proves challenging as the Javascript parser seems to have a distaste for

Hey there, I hope everything is going well! I've been working on a project that involves scanning the JSON data from reddit.com/r/pics. My goal is to extract a random image and display it on a webpage. The issue I'm facing is that Reddit's ...

Utilize Next.js and GSAP to dynamically showcase images upon hovering over the title

I have a dynamic list of titles that I want to enhance by displaying images when hovering over each title. The issue I'm facing is that when I hover over one title, all the images display at once. As a React beginner, I believe the solution should be ...

Uncovering the secrets of locating and deleting arrays with the power of jQuery

Is there a way to extract data from an array list and then have it automatically removed once displayed? let fruits = ["Banana", "Orange", "Watermelon"]; For instance, if I want to select the Watermelon element from the array. After retrieving and display ...

When working with data in Angular, make sure to use any[] instead of any in app.component.html and app.component.ts to avoid causing overload errors

I'm new to working with Angular, specifically using Angular 15. I have a Rest API response that I need to parse and display in the UI using Angular. To achieve this, I employed the use of HttpClient for making GET requests and parsing the responses. ...

Steering clear of inserting 'Array' into a database through autocomplete using Js, Ajax, and Json

I'm currently working on a script that auto-populates input fields based on the autocomplete feature of the first input field. Although the script works fine and everything looks good when I hit submit, the problem arises when I check the database. A ...

Enter key always causes the Bootstrap form to submit

I am working with a jquery function: $("#get-input").keyup(function (event) { if (event.keyCode === 13) { $("#get-data").click(); } }); $("#get-data").click(function (e) { var endpoint = $(".get-input").val(); if ($('#data-d ...

Having trouble with the Twitter share count URL - seeking out other options

Previously, I utilized the following Javascript function to retrieve the Twitter share count for a URL. Unfortunately, Twitter has discontinued providing the share count. Is there a more effective alternative available? // Twitter Shares Count $.getJSON ...

The JSX Configuration in TypeScript: Comparing ReactJSX and React

When working with Typescript and React, it's necessary to specify the jsx option in the compilerOptions section of the tsconfig.json file. Available values for this option include preserve, react, react-native, and react-jsx. { "compilerOptions": { ...

The elements of objects inside an array are not being displayed by Handlebars

Five months ago, my project code was running smoothly without any issues. However, now I am facing a problem where Handlebars is not displaying data in the list. Despite confirming that I am receiving an array of categories from the backend and being able ...