Utilizing a variable as a prop in a Vue component

I've been working on incorporating Vue components into an older project that currently renders HTML pages using JSP files on the server.

Some of the data is being rendered as variables inside script tags within the page.

Here's how a section of my page looks:

<body>
  <script>
  var mydata = {
    name: "Bob",
    age: 45
  }
  </script>

  <div id="app">
    <my-component v-bind:myprop="mydata"></my-component>
  </div>
</body>

While I could directly stringify my data into the prop attribute, I was wondering if anyone has a better approach in mind.

Answer №1

Automatically evaluate your variables and inject JSON into the props.

You could also mount your components in random parts of your backend-generated page outside a Vue app:
Mounting components individually without a root like #app

import './assets/main.css';

        import { createApp } from 'vue';

        const app = createApp({});

        const components = import.meta.glob('@/**/*.vue', { eager: true });
        Object.values(components).forEach(({ default: component }) => app.component(component.__name, component));

        const $app = document.querySelector('#app');

        for (const path in components) {
            const tag = path.match(/([^/]+).vue/)?.[1].split(/(?=[A-Z])/g).join('-');
            for (const $elem of $app.querySelectorAll(tag)) {
                for (const attr of $elem.attributes) {
                    if (!(attr.name[0] === ':' || attr.name === 'v-bind')) {
                        continue;
                    }
                    const fn = new Function('', `return JSON.stringify(${attr.value})`);
                    $elem.setAttribute(attr.name, fn());
                }
            }
        }

        app.mount('#app');
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <link rel="icon" href="/favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vite App</title>
</head>

<body>
    <script>
        const message = 'Hello world!';
        const subtitle = { content: 'And enjoy your sufferring!' }
    </script>
    <div id="app">
        <hello-world :subtitle="subtitle" :msg="message"></hello-world>
    </div>
    <script type="module" src="/src/main.js"></script>
</body>

</html>

https://i.sstatic.net/bu2nh.png

The project's source code:

const src='UEsDBBQAAAAIAKZp11buhulvuAAAAC4BAAAKABwALmdpdGlnbm9yZVVUCQADR36VZA6ElWR1eAsAAQToAwAABOgDAABlTkGOwjAMvPsVQdwq0T6BC9y48QAUEm9JFezKTrvb3+N0hUBwmfGMbM9s3Yl7hVyhaY2Axvsu4nXqq2pg8UJfGkVY/vX4sZ9RyL8bQBzxcuc4ZVRoD+fLubAgxKRlhZ2qQOAZxfe4lgg+A3RhGQVVuzlFZO1ehgZBJL1xMRe27hiTfXQxCQYbEqrzFN1PWgNnDVaga2DzHPGv2Hli0nZQJmgtwFuwTmxIZdam8qCj8FD9TBV/9/AAUEsDBAoAAAAAAKZp11YAAAAAAAAAAAAAAAAIABwALnM...

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

Issue encountered: Error in Node.js watchFile - "Undefined is not a function"

Just delving into the world of Node.js and experimenting with some basic code. I currently have the Node.js windows binary version 0.5.8 installed. Below is a snippet of my JavaScript code: var fs = require("fs"); fs.readFile('message.text ...

Set the Checkbox selections by utilizing the array values in the MUI DataGrid

In my MUI Datagrid, I have 2 columns for ID and City Name. There are only 3 cities represented in the table. Within a citizen object like this: const userMockup = { id: 1, name: "Citizen 1", cities: [1, 2], isAlive: true }; The cities ar ...

Trouble with displaying events on Angular UI-Calendar

I've been working with Angular UI Calendar and following the steps outlined on their website: http://angular-ui.github.io/ui-calendar/ Despite implementing everything correctly, I'm facing an issue where the events fetched from my API are not s ...

Unable to connect to 'highlight' as it is not a recognized attribute of 'code'

I have been experimenting with ngx-highlightjs and encountered an issue while trying to implement it in one of my module files. Due to having multiple modules, I am importing the HighlightModule only in the specific module where highlighting functionality ...

Discovering the 3D coordinates of a point that is perpendicular to the midpoint of a line

(I am working with Javascript/Typescript and Three.js) Given two vectors, let's say {x:1, y:3, z:5} and {x:7, y:8, z:10}, I have a direct straight line connecting them. At the midpoint of this line, envision a disc with a radius of 1 that is perpend ...

Is it possible to retrieve the object from a forEach loop?

Can an object be built using the results of a forEach loop? Here's my current approach: const data = {} object.rules.forEach(rule => { data[rule.name] = { body: [], type: rule.type } }) This is how I'd prefer to do it: const newData = obj ...

Showing the previous value in the Select2 select function

I have integrated Select2 as a searching dropdown feature on my website, but I am facing an issue where the previously selected value keeps being displayed even after selecting a new item from the list. Initially, I initialize the Select2 dropdown like th ...

Determining the height of dynamically rendered child elements in a React application

Looking for a way to dynamically adjust the heights of elements based on other element heights? Struggling with getting references to the "source" objects without ending up in an infinite loop? Here's what I've attempted so far. TimelineData cons ...

I've encountered an issue when attempting to use innerHTML for DOM manipulation

I've been attempting to remove a specific list item <li> from the inner HTML by assigning them proper IDs. However, I'm encountering difficulties in deleting it. How can I delete these list items after clicking on the cross button? Feel fr ...

What is the process of adding an array into a JSON object using the set() function in Firebase?

I am trying to add a new item to my firebase database with a specific JSON object structure: var newItem = { 'address': "Кабанбай батыр, 53", 'cityId': 1, 'courierName': "Ма ...

What is causing my Fabric.js canvas to malfunction?

Here is the link to my JSFiddle project: http://jsfiddle.net/UTf87/ I am facing an issue where the rectangle I intended to display on my canvas is not showing up. Can anyone help me figure out why? HTML: <div id="CanvasContainer"> <canvas id ...

Issues with React Material UI Modal refusing to open

I'm currently working on a React component using Material UI that is supposed to open a modal. Even though I can see the state toggle changing from false to true in the React Developer Console in Chrome, the modal does not open when I click the button ...

Is there a way to adjust the label elevation for a Material UI TextField component?

I am trying to enhance the appearance of a textfield label, but I am facing some challenges with my code. textStyle: { backgroundColor: '#1c1a1a', border: 0, borderRadius: 0, width: 400, height: 66, display: 'flex&a ...

Display or conceal checkboxes according to the elements in an array

After just starting to delve into Angular and javascript, I've been racking my brain for the past couple of days. I have this table in html where I need to display checkboxes based on certain conditions. Each row consists of 5 checkboxes, and what is ...

Is there a way to bring my popup closer to my button?

Check out my jsfiddle example here: https://jsfiddle.net/annahisenberg/ft10ersb/34/ Currently, I have the following code: <div id="more_options_popup" style={{ left: this.ref.current.offsetLeft - 140 + "px", top: this.ref.current.offsetTo ...

Effortless code formatting with VS Code for TypeScript and JavaScript

Does anyone know of any extensions or JSON settings that can help me format my code like this: if(true) { } else { } Instead of like this: if(true){ } else { } ...

Skip nodes in Polymer 1.0 by using ExcludeLocalNames

I recently attempted to transition from Polymer version 0.5 to 1.0 and came across a particular question: Is there a way to exclude certain nodes inside a paper-menu? In the previous version (0.5), you could use the attribute excludedLocalNames to achieve ...

Guide to clicking on a user and displaying their details in a different component or view using Vue.js router

Currently working on a Vuejs project that requires the following tasks: Utilize an API to fetch and display a list of users (only user names) on the home page. Create a custom search filter to find users based on their names. Implement functionalit ...

Keep sending HTTP requests until a 404 error is received

I need to keep sending http requests until I receive an error 404 response from one of them. There are a total of 21 pages and my current setup looks like this: _getAll = function () { var promises = []; var pages = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,1 ...

Validating a particular value using Regex in React Formik

First, I need to ensure that the field is validated for any characters not included in this set: /[ùûüÿ€’“”«»–àâæçéèêëïîôœ]/. If a user enters a character outside of this set, I want Yup to trigger an error message. Secondly, I ...