What is the best way to pass data from the server to a Vue CLI application?

I am looking for a way to connect my Vue CLI app to a server back-end. The server will send a view template along with data payload, and I need to inject that payload as JSON into the Vue app as a data property.

Here is a snippet of the index.html file generated by Vue CLI (I disabled filename hashing in vue.config.js):

<!DOCTYPE html>
<html lang=en>
    <head>
        <meta charset=UTF-8>
        <meta http-equiv=X-UA-Compatible content="IE=edge">
        <meta name=viewport content="width=device-width,initial-scale=1">
        <link href=/css/app.css rel=preload as=style>
        <link href=/css/chunk-vendors.css rel=preload as=style>
        <link href=/js/app.js rel=preload as=script>
        <link href=/js/chunk-vendors.js rel=preload as=script>
        <link href=/css/chunk-vendors.css rel=stylesheet>
        <link href=/css/app.css rel=stylesheet>
    </head>
    <body>
        <div id=app>
        </div>
        <script src=/js/chunk-vendors.js></script>
        <script src=/js/app.js></script>
    </body>
</html>

The main.js file contains:

import Vue from 'vue';
import SiteContainer from './components/layout/SiteContainer.vue';

new Vue({
    render: h => h(SiteContainer)
}).$mount('#app');

I want to pass the data received from the server template as follows:

<div id="app" :data="{{ json-string-of-data-payload-from-server }}">

In order to access this data in SiteContainer, I would use props like this:

props: [
    'data'
]

However, I faced issues where the :data property was lost due to the render method replacing the #app div with the site-container component.

I tried passing a second argument to render with data, but couldn't make it work. This approach also involves changes in main.js rather than the server-generated view template where the JSON data needs to be present for communication between the server and Vue app.

If you have any suggestions on how to successfully transfer data from the server-generated view template to the Vue CLI app, please let me know. Thank you!

Answer №1

I managed to solve the problem.

After declaring the SiteContainer component as a Vue.js component in the file main.js, I could easily utilize the component in the HTML document to achieve my desired outcome.

Specifically, these are the modifications made to the main.js file:

import Vue from 'vue';
import SiteContainer from './components/SiteContainer.vue';

Vue.component('SiteContainer', SiteContainer); // This is crucial.

new Vue({
    el: '#app'
});

Subsequently, the part of the HTML file containing the body was updated as shown below (replacing the existing #app div mentioned in the previous query):

<SiteContainer id="app" :data="{{ json-string-of-data-payload-from-server }}">
</SiteContainer>

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

React state is null and void

Experimenting with React and working on creating a basic chat application that will be linked to Firebase. I currently have one ChatApp container and one UserInput component. ChatApp -> import React from 'react'; import UserInput from &apos ...

What is the best way to target an element that does not exist yet?

I have a project for managing a todo list. When I click an "add" button, it creates a div element with another "add" button inside it. That part is easy. But now, I want to select that inner button so that I can use it to add a text input form inside the n ...

The Nodejs function exits before the internal function finishes executing

Currently, I am facing an issue where despite MongoDB returning the correct number of users (more than 0) when running console.log within collection.find(), the function userExists always returns false (0). I'm seeking guidance on how to ensure that ...

discovering obscured information using jquery

I am working on a code snippet where I need to hide the detailed content for display purposes and only show it during printing: <div> <ul> <li> <span style="font-size: 1.25em;"> <strong> ...

What is the best way to incorporate multiple HTML buttons that utilize the same JavaScript function within looped results?

My HTML page contains the following codes: <input type="text" class="woocommerce-Input woocommerce-Input--text input-text" name="metin" placeholder="Geben Sie Artikel Nr" style="width: 30%;"/><br/><br/> <input type="button" class="sin ...

Which Angular component, directive, or pipe would be best suited for creating dynamic HTML content similar to this?

(I am transitioning from React to Angular, so please bear with me if my question has a hint of React influence.) I am in need of developing an Angular component that can accept a string along with a list of terms within that string for displaying tooltips ...

The ASP.NET MVC3 form collection registers as 0 when performing a jQuery ajax post

I'm currently developing a project on ASP.NET MVC3. My current challenge involves POSTing to a method that should return a set of data using the jQuery.ajax api. However, upon handling the request on the server, I noticed that the form collection&apo ...

Unexpected Issues with the Ant Design Sidebar Layout Demo

My React webapp is utilizing the Ant design component framework version 4. I attempted to integrate this example from the Antd documentation into my webapp: https://codesandbox.io/s/ymspt However, when I implemented the code in my webapp, the result didn ...

The logo marquee unexpectedly bounces up and down at the end of every

Struggling with a JavaScript code issue. The Logo marquee suddenly jumps at the end of each loop: I've tried everything, but I can't seem to fix it and make it work as intended Here's the complete script that technically works, but causes ...

Generating hierarchical structures from div elements

Looking for guidance on how to parse a HTML page like the one below and create a hierarchical Javascript object or JSON. Any assistance would be much appreciated. <div class="t"> <div> <div class="c"> <input t ...

Is it possible to assign a class to the initial word within a designated class?

How can I customize the first and second word of a specific class in my code? This is an example of my current code: <h2 class="content-heading">Latest News</h2> I would like to achieve something similar to this: <h2 class="content-headi ...

How can I retrieve a value from the main model and assign it to an object in

I'm facing a simple dilemma. I want to extract the data from the main area of my Vue model and place it inside an object. I've tried using app.$data.name and also this.name, but unfortunately, I haven't been able to make it work without enco ...

Conceal the URL and any parameters upon successful completion of AJAX request

In my ajax js code, the solonreport.jsp file returns a URL link that connects to a local report server and generates an Excel report. However, when using this link with the window.open(json.url) function, the link and parameters are visible to the user. ...

An error was encountered with Ajax and JSONP due to an unexpected token causing a SyntaxError

Currently attempting to retrieve information from the host at 000webhost The data is in JSONP format: { "categories": { "category": [ { "name": "Android", "parent": "Computer Science", "ID": "2323" }, { ...

Best method for linking asynchronous requests using axios

Is it possible to make an API call using axios based on the response of another initial API call, all within asynchronous functions? I attempted the following approach with await/promise: function fetchUserDetails(userId) { return axios.get( "https://a ...

Numerous linkages facilitated by node-mongodb-native

Currently, I am working on a function aimed at inserting a document into a MongoDb database using the node-mongodb-native module. The function works perfectly fine, except when multiple documents are inserted back-to-back. To test how my function handles m ...

Here is a guide on updating HTML table values in Node.js using Socket.IO

I successfully set up socket io communication between my Node.js backend and HTML frontend. After starting the Node.js server, I use the following code to emit the data 'dRealValue' to the client side: socket.emit ('last0', dRealValue) ...

Click the button to save numerous images at once

We have added two mask images to the page. https://i.sstatic.net/uAbb7.png When a user clicks on a mask image, a file upload dialog box appears, allowing the user to upload their own image and click save. https://i.sstatic.net/V4kFA.png After clicking ...

Error message: "The use of Vue 3 refs in the render function is

I am facing an issue with my Vue component wherein the root element is set as ref="divRef". Strangely, when I try to access divRef.value inside the onMounted function, it returns undefined. Any assistance on this matter would be greatly appreci ...

Validate if cookie has been established in Javascript

Hello everyone! I am trying to redirect a user to another page when a cookie is set by clicking a button. <a href="" onClick="SetCookie('pecCookie','this is a cookie','-1')"><button type="button" name="accept" clas ...